在同一页面中多次使用相同对象的Knockout绑定

时间:2014-06-03 18:35:19

标签: mvvm knockout.js durandal

ViewModel:

var address = new function {
    var self = this;
    self.add1 = ko.observable();
    self.add2 = ko.observable();
    self.city = ko.observable();
    self.state = ko.observable();
    self.postal = ko.observable();
},
person = new funcion {
    var self = this;
    self.firstName = ko.observable();
    self.lastName = ko.observable();
    self.address = ko.observable(address);
},
company = new function {
    var self = this;
    self.salesPerson = ko.observable(person);
    self.shippingAddress = ko.observable(address);
    self.billingAddress = ko.observable(address);
};

查看:

<div>
    <h3>Shipping Address</h3>
    <span class="">Address1: </span><input type="text" data-bind="value:company.shippingAddress.add1">
    <span class="">Address2: </span><input type="text" data-bind="value:company.shippingAddress.add2">
    <span class="">City: </span><input type="text" data-bind="value:company.shippingAddress.city">
    <span class="">State: </span><input type="text" data-bind="value:company.shippingAddress.state">
    <span class="">Postal: </span><input type="text" data-bind="value:company.shippingAddress.postal">
</div>

<div>
    <h3>Billing Address</h3>
    <span class="">Address1: </span><input type="text" data-bind="value:company.billingAddress.add1">
    <span class="">Address2: </span><input type="text" data-bind="value:company.billingAddress.add2">
    <span class="">City: </span><input type="text" data-bind="value:company.billingAddress.city">
    <span class="">State: </span><input type="text" data-bind="value:company.billingAddress.state">
    <span class="">Postal: </span><input type="text" data-bind="value:company.billingAddress.postal">
</div>

问题:

在我看来,如果我在一个地方更改地址,它会随处变化。我需要使用observable,因为我也在同一页面中显示这些细节。

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

这没有任何意义 - 出于某种原因绑定是双向的,为什么要绑定到属性但不共享它?如果您希望每个人拥有不同的信息,只需使用不同的observable绑定到...

function address () {
    var self = this;
    self.add1 = ko.observable();
    self.add2 = ko.observable();
    self.city = ko.observable();
    self.state = ko.observable();
    self.postal = ko.observable();
},
company = new function {
    var self = this;
    self.salesPerson = ko.observable(person);
    self.shippingAddress = ko.observable(new address());
    self.billingAddress = ko.observable(new address());
};

在这种情况下,我使用的是匿名函数而不是构造函数。构造函数只会被计算一次并绑定到同一个对象。匿名函数将分别初始化两次。