[英]Knockout JS nested arrays. Adding items to a child array
Let's say I have something like this in Knockoutjs 假设我在Knockoutjs中有类似的内容
<pre data-bind="text: ko.toJSON($data, null, 2)">
{
"people":[
{
"name":"Thor",
"meta":[]
},
{
"name":"Hulk",
"meta":[]
}
]
}
</pre>
Javascript would be something like this: 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 HTML
<button data-bind="click: addHero">Add Hero With Meta</button>
Is it possible to add a "meta" under "Thor" or "Hulk"? 是否可以在“ Thor”或“ Hulk”下添加“ meta”?
I would first like to add the "meta" when a new parent item is inserted. 我首先要在插入新的父项时添加“元”。 The second step would be adding a meta to a target "hero". 第二步是将meta添加到目标“ hero”。
If you are calling addMeta
from within the context of a person
, then KO will pass the current data item as the first argument to your function. 如果您是在person
上下文中调用addMeta
,那么KO将把当前数据项作为第一个参数传递给您的函数。
So, you would be able to call item.meta.push
from within your handler. 因此,您可以从处理程序中调用item.meta.push
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.