Search code examples
knockout.jsknockout-2.0knockout-3.0

Multiple Observable Arrays


I'm trying to get some data from my server, create objects from this data, and then display it on my page in a foreach data bind.

Here is my code:

self.houses = ko.observableArray([]);
self.flats = ko.observableArray([]);

function Building(item, checked){
    self = this;
    self.id = item.id;
    self.name = item.nazwa;
    self.photo = '/' + item.pic;
    self.type = item.type_text;
    self.selected = ko.observable(checked);
}

$.getJSON("/api/getHouses", function(allData) {
    self.houses($.map(allData, function(item) { return new Building(item, 0) }));
});

$.getJSON("/api/getFlats", function(allData) {
    self.flats($.map(allData, function(item) { return new Building(item, 0) }));
});

When i run this code, I get an error:

self.flats is not a function

If I were to remove one of the getJSON functions, and only have one (either one), it works fine. Can I only have one observableArray at once?


Solution

  • It looks like the issue is that the "self" variable is being mutated by the Building function and no longer points to the root viewmodel when the ajax call returns. The fix might be as simple as placing "var" in front of self = this

    self.houses = ko.observableArray([]);
    self.flats = ko.observableArray([]);
    
    function Building(item, checked){
        //self = this; 
        var self = this; //the fix
        self.id = item.id;
        self.name = item.nazwa;
        self.photo = '/' + item.pic;
        self.type = item.type_text;
        self.selected = ko.observable(checked);
    }