0

我有两个送货类型的表格(包括姓名、地址、邮政编码等),还有一个按钮,上面写着“送货地址与送货地址相同”。基本上我试图做到这一点,以便当用户单击该按钮时,来自第一个字段的相同可观察值随后与第二个字段共享。我如何解决这个问题(可能是非常错误的)是通过设置两组可观察的,如下所示:

    self.firstName = ko.observable("");
    self.lastName = ko.observable("");
self.phoneNumber = ko.observable("");
self.address1 = ko.observable("");
self.address2 = ko.observable("");
self.city = ko.observable("");
self.state = ko.observable("");
self.postcode = ko.observable("");

    self.delFirstName = ko.observable("");
    self.delLastName = ko.observable("");
self.delPhoneNumber = ko.observable("");
self.delAddress1 = ko.observable("");
self.delAddress2 = ko.observable("");
self.delCity = ko.observable("");
self.delState = ko.observable("");
self.delPostcode = ko.observable(""); 

然后我尝试设置一个功能,单击该功能时,将共享运输详细信息。

self.sameDelAddress = function() {
    self.delFirstName() = self.firstName(self.firstName);
            self.delLastName() = self.lastName(self.lastName);
    self.delPhoneNumber() = self.phoneNumber(self.phoneNumber);
    self.delAddress1() = self.address1(self.address1);
    self.delAddress2() = ko.observable(self.address2);
    self.delCity() = ko.observable(self.city);
    self.delState() = ko.observable(self.state);
    self.delPostcode() = ko.observable(self.postcode);
}
4

1 回答 1

0

我认为您想要的是类似于下面的代码。看一下这个小提琴的一个工作示例。

选中复选框后尝试更新一个字段,您将看到另一个字段自动更新。

function addressModel() {
    var self = this;
    self.firstName = ko.observable("");
    self.lastName = ko.observable("");
    self.phoneNumber = ko.observable("");
    self.address1 = ko.observable("");
    self.address2 = ko.observable("");
    self.city = ko.observable("");
    self.state = ko.observable("");
    self.postcode = ko.observable("");
}

function deliveryModel(shipAddress, billAddress) {
    var self = this;
    self.shippingAddress = ko.observable(shipAddress);
    self.billingAddress = ko.observable(billAddress);
    self.addressesAreSame = ko.observable();

    self.addressesAreSame.subscribe(function(newValue){
        if(newValue===true){
            self.billingAddress(self.shippingAddress());
        }else{
            self.billingAddress(new addressModel());
        }
    });
}

var delivery = new deliveryModel(new addressModel(), new addressModel());
ko.applyBindings(delivery);

绑定示例:

<div data-bind="with: shippingAddress">
    Shipping Address<br />
    <input type="text" data-bind="value: address1" />
</div>
<div data-bind="with: billingAddress">
    Billing Address<br />
    <input type="text" data-bind="value: address1" />
</div>
<input type="checkbox" data-bind="checked: addressesAreSame" /> Billing same as shipping
于 2013-09-06T00:10:22.043 回答