![](/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.