敲除下拉表单绑定

时间:2012-07-05 17:37:22

标签: json knockout.js

我有一个用于添加多个地址的html表单:

http://i48.tinypic.com/jg2ruo.png

这种方式如果我更改地址类型选择,整个表单必须绑定到正确的json地址对象:

var jsonAddresses = { Addresses:
            [
                { AddressType: 1, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" },
                { AddressType: 2, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" },
                { AddressType: 3, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" },
                { AddressType: 4, Address1: "", Address2: "",Province:"",City:"",State:"",PostalCode:"",Municipal:"" }
            ] 
         };

我用Jquery用很多代码实现了这个,但我想知道如何用Knockout做到这一点。我的想法是没有固定的json对象,只有4种类型的地址,我想只有1个json对象,如果我选择不在数组中的地址类型,那么对象就会被添加和绑定,如果地址类型已经存在于数组中,然后绑定它。然后我可以有一个“删除”链接,当点击时,从阵列中删除所选的地址类型对象。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我猜这一点,因为它并不完全清楚。您需要一个表单来编辑地址,并使用下拉列表选择您正在编辑的地址。我把working fiddle放在了一起,但这里有重要的部分。

您有一个Address对象的概念,这是可观察的,因为您将更新值。然后你需要一个viewmodel来跟踪所有的地址,有一些selected地址的概念,以及添加新地址的能力。这是不明确的部分,所以我只使用New Address按钮。如果您有其他想法,请告诉我。除了状态列表和初始地址数据(两者都应该来自服务器)之外,这就是所有代码,正如你所看到的,淘汰赛让它变得非常简单。

HTML:

<select data-bind="options: addresses, optionsText: 'typeName', value: selectedAddress"></select>
<div data-bind="with: selectedAddress">
    Name: <input data-bind="value: typeName" /></br>
    Line1: <input data-bind="value: address1" /></br>
    Line2: <input data-bind="value: address2" /></br>
    City: <input data-bind="value: city" /></br>
    State: <select data-bind="options: $parent.states, value: state"></select></br>
    Postal Code: <input data-bind="value: postalCode" />
</div>
<button data-bind="click: addAddress">New Address</button>
<button data-bind="click: deleteAddress">Remove Address</button>

的ViewModels:

var Address = function(address) {
    this.id = ko.observable(address.AddressType || 0);
    this.typeName = ko.observable(address.TypeName || '');
    this.address1 = ko.observable(address.Address1 || '');
    this.address2 = ko.observable(address.Address2 || '');
    this.city = ko.observable(address.City || '');
    this.state = ko.observable(address.State || '');
    this.postalCode = ko.observable(address.PostalCode || '');
};

var App = function(addressList) {
    var self = this;
    self.states = states;
    self.addresses = ko.observableArray(ko.utils.arrayMap(addressList,
          function(i) { return new Address(i); }
    ));
    self.selectedAddress = ko.observable(self.addresses[0]);

    self.addAddress = function() {
        var newId = self.addresses()[self.addresses().length -1].id + 1;
        var newAddress = new Address({AddressType: newId});
        self.addresses.push(newAddress);
        self.selectedAddress(newAddress);
    };

    self.deleteAddress = function() {
        self.addresses.remove(self.selectedAddress());
        self.selectedAddress(self.addresses[0]);
    };
};

EDIT1 :添加了删除按钮。这是演示,显然当数组为空时你会想要一些安全逻辑。