Q:
如果你的ViewModel裡有兩個Observable屬性,分別為firstName與lastName,但若你想顯示的是fullName呢?
如何顯示羅羅亞·索隆?
var myViewModel() {
firstName: = ko.observable('索隆');
lastName: = ko.observable('羅羅亞');
}
firstName: = ko.observable('索隆');
lastName: = ko.observable('羅羅亞');
}
A:
使用computed Observables。
Computed Observable
$(window).ready(function (){
var myViewModel = {
firstName: ko.observable('索隆'),
lastName: ko.observable('羅羅亞'),
fullName: null
};
myViewModel.fullName = ko.computed(function(){
return myViewModel.firstName() + '·' + myViewModel.lastName();
},myViewModel);
ko.applyBindings(myViewModel);
});
Bind
全名:<span data-bind="text:fullName"></span>
結果:
全名:索隆·羅羅亞
Note:Ko.computed的第二個參數使用了 myViewModel ,若沒有這個值,computed將無法使用firstName與lastName兩個參考,這是javascript範圍域的關係,第二個參數需要傳入想被computed操作的物件參考。
使用JQuery來改變firstName:
$('#btn').click(function(){
myViewModel.firstName('阿隆索');
});
DOM上增加一個input:
全名:<span data-bind="text:fullName"></span></br>
<input id="btn" type="button" value="更改firstName"/>
click button後結果:
全名:阿隆索·羅羅亞
Note:computed observables依賴於一個或多個其它的observables,當所依賴的observable發生變化,computed observables也會跟著更新。
Q:
那這只有讀取,那寫入呢?
具有write功能的computed
$(window).ready(function(){
function MyViewModel() {
this.firstName = ko.observable('索隆');
this.lastName = ko.observable('羅羅亞');
this.fullName = ko.computed({
read: function () {
return this.firstName() + "·" + this.lastName();
},
write: function (value) {
//以點號為基準來拆解
var lastSpacePos = value.lastIndexOf('·');
if(lastSpacePos > 0) {
//拆解字串取回firstName
this.firstName(value.substring(0, lastSpacePos));
//拆解字串取回lastName
this.lastName(value.substring(lastSpacePos + 1));
}
},
owner: this
});
}
//啟動knockoutjs的bind功能
ko.applyBindings(new MyViewModel());
});
function MyViewModel() {
this.firstName = ko.observable('索隆');
this.lastName = ko.observable('羅羅亞');
this.fullName = ko.computed({
read: function () {
return this.firstName() + "·" + this.lastName();
},
write: function (value) {
//以點號為基準來拆解
var lastSpacePos = value.lastIndexOf('·');
if(lastSpacePos > 0) {
//拆解字串取回firstName
this.firstName(value.substring(0, lastSpacePos));
//拆解字串取回lastName
this.lastName(value.substring(lastSpacePos + 1));
}
},
owner: this
});
}
//啟動knockoutjs的bind功能
ko.applyBindings(new MyViewModel());
});
DOM
<span data-bind="text:firstName"></span></br>
<span data-bind="text:lastName"></span></br>
<input type="text" data-bind="value:fullName"/>
結果:
一開始呈現了 [索隆·羅羅亞],當再輸入框中輸入[蒙其D·魯夫],在span中所bind的firstName與lastName會自動改變,由於這個範例使用點號作字串拆解依據,所以輸入時需使用·號做區隔。
沒有留言:
張貼留言