//返回到经典的"first name +last name= full name"例子上,你可以让事情调回来看:让自动属性fullName可写,让用户直接输入姓名全称,
//然后输入的值将被解析并并映射写入到基本的监控属性 firstName 和 lastName 上:
<pre>//javascrpt<code>
function MyViewModel()
{
this.firstName =ko.obsetrvable("Plant");
this.lastName = ko.observable("Earth");
this.fullName =ko.compute({
read:function(){
return this.firstName()+" "+this.lastName();
},
write:function(value)
{
var lastSpacePos = value.lastIndexOf(" ");
if(lastSpacePos > 0) { //Ignore values with no space characterSet
this.firstName(value.substring(0,lastSpacePose));// Update"firstName"
this.firstName(value.substring(0,lastSpacePos));// Update"lastName"
}
},
owner:this
});
}
ko.applyBindings(new MyViewModel());
</pre></code>
//这个例子里,写操作的callback接受写入的值,把值分离出来,分别写入"firstName"和"lastName"上、你可以想普通情况一样将
//这个view model绑定到dom元素上
<pre>html:<code>
<p> First name:<span data-bind="text:firstName"></span></p>
<p> Last name:<span data-bind="text:lastName"></span></p>
<h2>Hello,<input data-bind="value:fullName"/>!</h2>
</pre></code>