敲除复杂的绑定

时间:2013-11-29 14:21:43

标签: knockout.js knockout-2.0

请看看我的jsFiddle http://jsfiddle.net/chugh97/PQvFc/23/

我可以添加多个手机没有问题并删除它们,但是当我添加多个地址时它不起作用。我只能添加一个地址。

    var user = { id: 1 };

var UserModel = function(data) {
    var self = this;
    self.phones = ko.observableArray([]);
    self.addresses = ko.observableArray([]);

    self.addPhone = function(phone) {
        self.phones.push({
            type: phone.type,
            number: phone.number
        });
    };

    self.removePhone = function(phone) {
        self.phones.remove(phone);
    };

    self.addAddress = function() {
        self.addresses({
            line_1: "",
            line_2: "",
            town: "",
            postcode: "",
            country: ""
        });
    };

    self.removeAddress = function(address) {
        self.addresses.remove(address);
    };

    self.save = function() {
        //alert(JSON.stringify(ko.toJS(self), null, 2));
        self.lastSavedJson(JSON.stringify(ko.toJS(self), null, 2));
    };

    self.lastSavedJson = ko.observable("")
};


    ko.applyBindings(new UserModel(user));

2 个答案:

答案 0 :(得分:2)

这是更新的小提琴:http://jsfiddle.net/PQvFc/28/

在您发布的小提琴链接中,delivery_addressobservable,而不是observableArray,您添加和删除的代码未将地址传递给该函数。

我不是100%确定这会解决您的问题,但它会使地址的工作方式与您的电话号码相同。

答案 1 :(得分:0)

你需要调用地址数组上的push来添加多个项目。

更新了以下示例代码:

    var user = { id: 1 };

var UserModel = function(data) {
    var self = this;
    self.phones = ko.observableArray([]);
    self.addresses = ko.observableArray([]);

    self.addPhone = function(phone) {
        self.phones.push({
            type: phone.type,
            number: phone.number
        });
    };

    self.removePhone = function(phone) {
        self.phones.remove(phone);
    };

    self.addAddress = function() {
        self.addresses.push({
            line_1: "",
            line_2: "",
            town: "",
            postcode: "",
            country: ""
        });
    };

    self.removeAddress = function(address) {
        self.addresses.remove(address);
    };

    self.save = function() {
        //alert(JSON.stringify(ko.toJS(self), null, 2));
        self.lastSavedJson(JSON.stringify(ko.toJS(self), null, 2));
    };

    self.lastSavedJson = ko.observable("")
};


    ko.applyBindings(new UserModel(user));