无法在Knockout中绑定嵌套的JSON

时间:2013-02-12 11:51:58

标签: json knockout.js nested bind

我正在尝试将JSON传递给淘汰赛并展示它,我已经设法为前几个元素做了这样的事情。但是我遇到了嵌套对象的问题。我想要实现的是显示每个A1,A2,A3 / B1,B2,B3的desc和value字段..

我查看了一百万个示例并尝试了各种版本,但仍无法弄清楚映射的工作原理。

非常感谢您的帮助。

JS:

function jsonSubsetModel (desc,value){
    var self = this;
    self.desc = ko.observable(desc);
    self.value = ko.observable(value);
    }


    var myModel = function(){
        var jsonUrl = '/myjson.json';
        var self = this;
        var mapped = {};

        //Data
        self.date = ko.observable();
        self.time = ko.observable();

        self.set1 = ko.observableArray([]);
        self.set2 = ko.observableArray([]);



    $.getJSON(jsonUrl,function (data) {     
    self.date(data.Date);
    self.time(data.Time);   
    self.img(data.ImgURL);

    mapped = ko.mapping.fromJS(data);
    self.set1(mapped.SET1);
    self.set2(mapped.SET2);             
    });

    };  

    ko.applyBindings(new myModel());    

HTML:

<!-- This works -->
    <span data-bind="text: date"></span><br>
    <span data-bind="text: time"></span><br>
    <span data-bind="text: img"></span><br>

<!-- This doesn't -->    
    <p data-bind = "foreach:{data: set1, as:'subset'}">
    <span data-bind="text: subset.desc"></span>
    <span data-bind="text: subset.value"></span>    
    </p>

JSON:

{    
"Date":"21/02/2013",
"Time":"13:55",    
"SET1": {       
            "A1":{          
            "desc":"descA1",
            "value":"30",               
            },
            "A2":{          
            "desc":"descA2",
            "value":"30",
            },
            "A3":{          
            "desc":"descA3",
            "value":"30",
            }                                           
    },

    "SET2": {       
            "B1":{          
            "desc":"descA1",
            "value":"30",
            },
            "B2":{          
            "desc":"descA1",
            "value":"30",
            },
            "B3":{          
            "desc":"descA1",
            "value":"30",
            }                       
    }
}

1 个答案:

答案 0 :(得分:3)

knockout.js foreach适用于Array。你提供的是一个对象。将您的对象更改为:

"SET1": [      
            {          
            "desc":"descA1",
            "value":"30",               
            },
            {          
            "desc":"descA2",
            "value":"30",
            },
            {          
            "desc":"descA3",
            "value":"30",
            }                                           
    ],