Knockout JS嵌套数组。将项添加到子数组

时间:2012-11-06 04:05:03

标签: javascript knockout.js

假设我在Knockoutjs中有类似的东西

<pre data-bind="text: ko.toJSON($data, null, 2)">
{
    "people":[
        {
            "name":"Thor",
            "meta":[]
        },
        {
            "name":"Hulk",
            "meta":[]
        }
    ]
}
</pre>

Javascript会是这样的:

function SuperheroViewModel() {
    var self = this;
    self.people = ko.observableArray();
    self.people.meta = ko.observableArray();

    self.people.push(new Person({name: 'Thor'}));
    //self.people.push(new Person({name: 'Hulk'}));

    self.addHero= function() {
        self.people.push(
            new Person({
                name: 'Wolverine'
            })
        );

        //self.meta.push(new Meta({sex: 'male'});
    }
}

ko.applyBindings(new SuperheroViewModel());
​

HTML

<button data-bind="click: addHero">Add Hero With Meta</button>

是否可以在“Thor”或“Hulk”下添加“meta”?

我首先要在插入新的父项时添加“meta”。第二步是向目标“英雄”添加元。

1 个答案:

答案 0 :(得分:1)

如果您在addMeta的上下文中调用person,则KO会将当前数据项作为您函数的第一个参数传递。

因此,您可以在处理程序中调用item.meta.push