Search code examples
knockout.jsknockout-mvc

Knocked out by nested editor 3 or more levels deep


When trying to extend the live example for a nested editor provided on the KO site ( http://jsfiddle.net/rniemeyer/gZC5k/ ) to change the layout and add deeper levels, I've not been able to tackle two issues.

although I was able to get to this stage http://jsfiddle.net/gZC5k/955/

I got stuck with somewhere in building the correct hierarchy in the model,

    var ContactsModel = function (contacts) {
var self = this;
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
    return {
        firstName: contact.firstName,
        lastName: contact.lastName,
        phones: ko.observableArray(contact.phones),
        addresses: ko.observableArray(contact.addresses)
    };
}));

The two issues are:

  • not being able to add a new "Call" to a "Phone" that is loaded in the initial dataset (When I create a new Phone, I can add "Calls")
  • not being able to delete "Calls".

    self.removeCall = function (call) {
    $.each(self.phones(), function () {
        this.calls.remove(call)
    })
    

    };

Any help appreciated.


Solution

  • I have fixed your model.Replace this code in fiddle, and then check

    It works perfect

    self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
        return {
            firstName: contact.firstName,
            lastName: contact.lastName,
            addresses: ko.observableArray(contact.addresses),
            phones: ko.observableArray(ko.utils.arrayMap(contact.phones, function (phone) {
                return{
                    type: phone.type,
                    number: phone.number,
                    calls: ko.observableArray(phone.calls)
                };
            }))
        };
    }));