Skip to content Skip to sidebar Skip to footer

Knockoutjs Nested Observablearrays

I have some trouble with knockout nested observableArrays. My Data looks like this: var myData = { Id: 123, Name: 'string here', Categories: [ { Id:

Solution 1:

Create viewmodels for categories & products. categoryViewModel should contain a function to add products and the root viewmodel should contain a function to add categories:

Root viewmodel:

viewModel = function () {
    var self = this;

    menuItem = menuItem || {
        Id: 0,
        Name: null,
        Categories: []
    };

    this.Id = ko.observable(menueItem.Id);
    this.Name = ko.observable(menueItem.Name);
    this.Categories = ko.observableArray();

    this.addCategory = function(category) {
        self.Categories.push(newcategoryViewModel(category));
    }

    // create category viewmodels and add them to this root viewmodelfor (var i = 0, l = menuItem.Categories.length; i < l; i++) {
        self.addCategory(menuItem.Categories[i]);
    }
     // ...
}

Category viewmodel:

categoryViewModel = function(categoryObj) {  
    var self = this;

    categoryObj = categoryObj || {
        Id: 0,
        Name: null,
        Products: [],
    };
    this.Id = ko.observable(categoryObj.Id);
    this.Name = ko.observable(categoryObj.Name);
    this.Products = ko.observableArray();

    this.addProduct = function(product) {
        self.Products.push(newproductViewModel(product);
    }

    // create product viewmodels and add them to this category viewmodelfor (var i = 0, l = categoryObj.Products.length; i < l; i++) {
        self.addCategory(categoryObj.Products[i]);
    }
}

Product viewmodel:

productViewModel = function(productObj) {  
    var self = this;

    productObj = productObj || {
        Id: 0,
        Name: null,
        SomethingElse: null,
    };
    this.Id = productObj.Id;
    this.Name = productObj.Name;
    this.SomethingElse = productObj.SomethingElse;
}

You will have:

viewmodel {
    Id(),
    Name(),
    Categories() : [
        categoryViewModel = {
            Id(),
            Name(),
            Products(): [
                productViewModel = {
                    Id,
                    Name,
                    SomethingElse
                }
                ...
            ]
        },
        ...
    ]
}

Post a Comment for "Knockoutjs Nested Observablearrays"