Mapping deeply hierarchical objects to custom classes using knockout mapping plugin

前端 未结 4 1010
一生所求
一生所求 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:32

    If you don't want the nested mappingOptions (creating a ko map object for each node level), you can take advantage of the fact the ko mapping options for create give you access to the parent object. Something like this:

    function Folder(parent,data) {
        var self = this;
        self.parent = parent;
        ko.mapping.fromJS(data, self.map, self);
    }
    
    Folder.prototype.map = {
        'folders': {
            create: function(options) {
                var folder = new Folder(options.parent,options.data);
                return folder;
            }
        }
    }
    
    var data = { name:"root", folders: [ {name:"child", folders: [] } ] };
    var root = new Folder(null, data);
    

    That way you only have 1 copy of the map, in your class prototype (or could be any function). If you want Folder.parent to be an observable as well, you could do data.parent = parent; inside the map function and not pass as a parameter to your Folder constructor, or do that inside the folder constructor instead of self.parent = parent;

提交回复
热议问题