1

我从服务器收到一个复杂的 JSON。让它成为下一个:

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"}
                ]}]
        }]
    }];

所以我有一个对象列表,每个对象都包含名称和项目属性。Items 是类似对象列表的属性,每个对象都包含 name 和 subItems 属性。subItems 属性与上一个相同,并具有 name 和 children 属性。children 是我的实体列表。我使用映射来填充我的 ViewModel。首先,我无法想象如何id在我的实体中设置为键。我想知道如何“潜入”它。此外,我需要扩展我的实体。像下一个示例一样添加计算属性:

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

我不想创建 js 类,因为在这种情况下我看不到映射的好处。在这种情况下,我可以实现手动映射。对我来说会更清楚。

因此,欢迎任何想法、建议或批评。

PS:我已经搜索/阅读过类似的主题

4

1 回答 1

1

您必须显式声明子视图模型才能获得此行为,但您仍然可以从完成所有映射中受益

http://jsfiddle.net/uXMhA/

ChildViewModel = function(data) {
    ko.mapping.fromJS(data, {}, this);
    this.computProp = ko.computed(function() {
        return this.name() + this.status();
    }, this);
};
于 2013-01-25T23:20:18.570 回答