简体   繁体   中英

knockout nested model observableArray is not defined

I have a pretty basic structure, with 2 nested models

model1
----observableArray of model2

model2
----observableArray of model3

i am able to bind to model1, and iterate over model2 array (using a foreach) and bind to the properties.

the problem is when i try to bind to model3 array:

[root] data-bind(blah: model1.property1 // OK
[root] foreach: model2Array             // OK 
    data-bind(blah: model2.property1)   // OK
    data-bind(blah: model2.model3Array) // Undefined exception

model1, model2, model3 are all defined the same way

var model3 = function(data) {
        var self = this;
        if (data) ko.mapping.fromJS(data, {}, self);
        else ko.mapping.fromJS(_model2Template, {}, self);
}
var model2 = function(data) {
        var self = this;
        if (data) ko.mapping.fromJS(data, {}, self);
        else ko.mapping.fromJS(_model2Template, {}, self);

        self.model3Array = ko.observableArray();
        self.addModel3 = function(m3) {
            if (m3) self.model3Array.push(m3)
            else self.model3Array.push(new model3);
        }
}
var model1 = function(data) {
        var self = this;
        if (data) ko.mapping.fromJS(data, {}, self);
        else ko.mapping.fromJS(_model1Template, {}, self);

        self.model2Array = ko.observableArray();
        self.addModel2 = function(m2) {
            if (m2) self.model2Array.push(m2)
            else self.model2Array.push(new model2);
        }
}

window.model1 = new model1();
ko.applyBindings(model1);

interesting part is that the observableArray on model1 works as expected.. the thing breaks down when i try to access an array on one of the objects in root array!

UPDATE

added the functions used to add new objects in the array

I am guessing i need to provide a mapping with create events for each array, but not sure where that would go

figured it out.. the problem was in my add handler

    self.addModel3 = function(m3) {
        if (m3) self.model3Array.push(m3)
        else self.model3Array.push(new model3);
    }

thought i was clever and assumed that it would be called with no parameters unless i explicitly specified them,

but declaring a click handler this way:

<button ... data-bind="click: addModel2"> 

WILL in fact pass the model as first parameter. so i was actually adding root model instead of the nested model i expected. and there were no javascript errors, just the property i expected to be on there was missing in the end

From your example, model2.model3array should be model2.model3Array ?

Hth,
Aaron

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM