Remove an element from observableArray inside another observableArray in knockout

 ̄綄美尐妖づ 提交于 2020-01-05 12:08:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!