Let’s say I have something like this in Knockoutjs
<pre data-bind="text: ko.toJSON($data, null, 2)">
{
"people":[
{
"name":"Thor",
"meta":[]
},
{
"name":"Hulk",
"meta":[]
}
]
}
</pre>
Javascript would be something like this:
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>
Is it possible to add a “meta” under “Thor” or “Hulk”?
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”.
If you are calling
addMetafrom within the context of aperson, then KO will pass the current data item as the first argument to your function.So, you would be able to call
item.meta.pushfrom within your handler.