//返回到經(jīng)典的"first name +last name= full name"例子上爱榔,你可以讓事情調(diào)回來(lái)看:讓自動(dòng)屬性fullName可寫(xiě),讓用戶直接輸入姓名全稱雄卷,
//然后輸入的值將被解析并并映射寫(xiě)入到基本的監(jiān)控屬性 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>
//這個(gè)例子里搓蚪,寫(xiě)操作的callback接受寫(xiě)入的值,把值分離出來(lái)丁鹉,分別寫(xiě)入"firstName"和"lastName"上妒潭、你可以想普通情況一樣將
//這個(gè)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>