Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout custom mapping for nested objects

I have a JSON object like:

{
    id:"a",
    type:"simple",
    children:[
        {
            id:"a.1",
            type:"simple",
            children:[
                {
                    id:"a.1.1",
                    type:"simple",
                },
                {
                    id:"a.1.2",
                    type:"simple",
                }
            ]
        },
        {
            id:"a.2",
            type:"simple",
        },
        {
            id:"a.2",
            type:"simple",
        }
    ]
}

I am trying to use the knockout mapping plugin to create a custom selected property for all children objects like this:

{
    id:"a",
    type:"simple",
    children:[
        {
            id:"a.1",
            type:"simple",
            selected:true,
            children:[
                {
                    id:"a.1.1",
                    type:"simple",
                    selected:true
                },
                {
                    id:"a.1.2",
                    type:"simple",
                    selected:true
                }
            ]
        },
        {
            id:"a.2",
            type:"simple",
            selected:true
        },
        {
            id:"a.2",
            type:"simple",
            selected:true
        }
    ]
}

My code looks like this at the moment:

getMapping : function() {
    var childModle = function(data) {
        data.selected = false;
        ko.mapping.fromJS(data, {}, this);
        };
        var mapping = {
            "children" : {
                create : function(options) {
                    return new childModle(options.data);
                }
            }
        };
    return mapping;
},

var mapping =  this.getMapping();
var mappedModel = ko.mapping.fromJS(model, mapping);

This only works for the top level children. The 2-n level children are not created using my mapping.

* My model can have an infinite amount of nested levels *

My question is how can I make the children create apply for all nested children?

like image 429
user1904839 Avatar asked Dec 14 '12 18:12

user1904839


1 Answers

You would want to pass the mapping options into the ko.mapping.fromJS call that you are making inside the childModle constructor function.

like image 129
RP Niemeyer Avatar answered Oct 11 '22 03:10

RP Niemeyer