简体   繁体   中英

knockout: extending mapping to complex JSON

I receive a complex JSON from the server. Let it be next:

var data = [{
    name: "name1",
    items:[
        {
        name:"name11",
        subItems:[{
                name:"name111",
                children[
                    {id:1,name:"child1111",status:"good"},
                    {id:2,name:"child1112",status:"bad"},
                    {id:3,name:"child1113",status:"good"}
                ]},
                {
                name:"name112",
                children[
                    {id:4,name:"child1121",status:"good"}]
                }]
        },
        {
        name:"name12",
        subItems:[{
                name:"name121",
                children[
                    {id:5,name:"child1211",status:"bad"}]
                }]
        }]
    },
    {
    name: "name2",
    items:[
        {
        name:"name21",
        subItems:[{
                name:"name111",
                children[
                {id:7,name:"child2111",status:"good"}
                ]}]
        }]
    }];

So I have the list of objects each one contains name and items properties. Items is property of the similar list of objects each one contains name and subItems properties. subItems property same to previous and has name and children properties. children is list of my entities. I use mapping for filling my ViewModel. First of all I can't image how to set as key id in my entity. I am wondering how to "dive" to it. Moreover, I need to extend my entity. Add the compute property like next example:

computProp: ko.computed(function() {return name+status;})

I don't want to create js classes, because I don't see benefits of mapping on this case. I can implement manual mapping in this case. It would be more clear for me.

So any idea, suggesting or critics are welcome.

PS: I have searched/read similar topics

You must explicit declare the children viewmodel to get this behaviour, but you still benefit from getting all the mapping done

http://jsfiddle.net/uXMhA/

ChildViewModel = function(data) {
    ko.mapping.fromJS(data, {}, this);
    this.computProp = ko.computed(function() {
        return this.name() + this.status();
    }, this);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM