Knockout complex binding

83 Views Asked by At

Pls have a look at my jsFiddle http://jsfiddle.net/chugh97/PQvFc/23/

I can add multiple phones no problems and remove them, but when I add multiple address it does not work. I can add one address only.

    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

There are 2 best solutions below

0
Tanner On BEST ANSWER

Here's the updated fiddle: http://jsfiddle.net/PQvFc/28/

In the fiddle link you posted, delivery_address was an observable, not an observableArray and your code to add and remove didn't pass the address to the function.

I'm not 100% sure this will resolve your problem, but it makes the addresses work in the same way that your phone numbers work.

0
KevB On

You need to call push on the addresses array to add multiple items into it.

Updated sample code shown below:

    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));