Mapping deeply hierarchical objects to custom classes using knockout mapping plugin

前端 未结 4 1013
一生所求
一生所求 2020-12-07 18:06

Using the knockout mapping plugin ( http://knockoutjs.com/documentation/plugins-mapping.html ) can you map a deeply hierachical object?

If I have an object with mult

4条回答
  •  情书的邮戳
    2020-12-07 18:28

    I used the approach in this answer to create a hierarchy of checkboxes where nodes with children are collapsible and when you check/uncheck the parent its descendants get checked/unchecked.

    View Model

    var Category = function(data, parent) {
        var self = this;
        self.name = data.name;
        self.id = data.id;
        self.parent = parent;
        self.categoryChecked = ko.observable(false);
        ko.mapping.fromJS(data, self.map, self);
    };
    
    // This will add a "map" to our category view model
    Category.prototype.map = {
        'sub_categories' : {
            create: function(options){
                var category = new Category(options.data, options.parent);
                category.parent.categoryChecked.subscribe(function(value){
                    category.categoryChecked(value);
                });
                return category;
            }
        }
    };  
    

    HTML (view)

        

提交回复
热议问题