问题
After finishing knockout tutorial working with lists and collections I decided to go a little bit further to implement two level nesting with knockout.
The structure of my ViewModel looks like this:
function ViewModel() {
this.elements = ko.observableArray([{
id: 1,
txt: 'first',
el: ko.observableArray(['first', 'second'])
},{
id: 2,
txt: 'second',
el: ko.observableArray(['first', 'third'])
},{
id: 3,
txt: 'third',
el: ko.observableArray(['fourth', 'fifth'])
}]);
this.remove = function(el){
console.log(el);
}
}
So this is like Observable array in observable array. And I am outputting this with a simple 2 foreach view-binding:
<div data-bind="foreach: elements">
<span data-bind="text: txt"></span>
<ul data-bind="foreach: el">
<li data-bind="text: $data, click: $root.remove">
</ul>
</div>
The problem is with remove statement (full code is in the fiddle). With what I have so far I am failing to delete the element. Function gives me only the value of the element I want to delete like first
which is not enough to uniquely identify what exactly do I need to delete (is this first in the first array or the second).
So is there a way to correctly remove the element from observableArray inside of observableArray?
回答1:
You can pass additional arguments to the click handler like the $parent
which is the parent context:
<li data-bind="text: $data, click: function() { $root.remove($data, $parent) }"/>
Then in your remove
you can access the parent collection through the second argument and remove the current element from it:
this.remove = function(data, parent){
parent.el.remove(data);
}
Demo JSFiddle.
来源:https://stackoverflow.com/questions/22127275/remove-an-element-from-observablearray-inside-another-observablearray-in-knockou