![](/img/trans.png)
[英]How can i know change in knockout.js ViewModel just by change in its observable property?
[英]In a program using knockout.js with multiple ViewModels, how can know one specific view model is changed by change in the property?
我正在使用帶有knockout的asp.net mvc進行數據綁定。 我有三個視圖模型,如下所示:
function PersonViewModel() {
this.firstName = ko.observable("@Model.FirstName");
this.lastName = ko.observable("@Model.LastName");
}
function ContactViewModel() {
this.homePhone = ko.observable("@Model.HomePhone");
this.mobile = ko.observable("@Model.Mobile");
}
function AddressViewModel() {
this.city = ko.observable("@Model.City");
this.street = ko.observable("@Model.Street");
}
var pvm = new PersonViewModel();
var avm = new AddressViewModel();
var cvm = new ContactViewModel();
var pNode = $("#personal-information").get(0);
var aNode = $("#address-information").get(0);
var cNode = $("#contact-information").get(0);
ko.applyBindings(pvm, pNode);
ko.applyBindings(avm, aNode);
ko.applyBindings(cvm, cNode);
Html如下:
<div id="personal-information">
<input data-bind="value: firstName" type="text" >
<input data-bind="value: lastName" type="text" >
</div>
<div id="contact-information">
<input data-bind="value: homePhone" type="text" >
<input data-bind="value: mobile" type="text" >
</div>
<div id="address-information">
<input data-bind="value: city" type="text" >
<input data-bind="value: street" type="text" >
</div>
這些輸入字段的默認值是從數據庫中的3個不同表中獲取的。 我想編輯這些值並更新這些表中的數據。
如果我只更改PersonViewModel中的輸入值,我想創建一個只調用person表的更新查詢的ajax請求。 對於地址和聯系人ViewModel也一樣。 我知道如何制作ajax請求。
但我的問題是:使用knockoutJs,我怎么知道只有那些特定的ViewModel被更新以便我可以留下其余的呢?
對於每個View Model,您可以創建一個其他observable可以訂閱的方法。 例如,對於PersonViewModel:
function PersonViewModel() {
this.firstName = ko.observable("@Model.FirstName");
this.lastName = ko.observable("@Model.LastName");
this.updatePerson = function () { /* AJAX */ };
// subscriptions
this.firstName.subscribe(this.updatePerson);
this.lastName.subscribe(this.updatePerson);
}
因此,只要firstName或lastName的值發生更改,就會觸發updatePerson方法。
其他視圖模型的想法相同
function ContactViewModel() {
this.homePhone = ko.observable("@Model.HomePhone");
this.mobile = ko.observable("@Model.Mobile");
this.updateContact = function () { /* AJAX */ };
// subscriptions
this.homePhone.subscribe(this.updateContact);
this.mobile.subscribe(this.updateContact);
}
function AddressViewModel() {
this.city = ko.observable("@Model.City");
this.street = ko.observable("@Model.Street");
this.updateAddress = function () { /* AJAX */ };
// subscriptions
this.city.subscribe(this.updateAddress);
this.street.subscribe(this.updateAddress);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.