从敲除中的另一个observableArray内部的observableArray中移除一个元素 [英] Remove an element from observableArray inside another observableArray in knockout

查看:121
本文介绍了从敲除中的另一个observableArray内部的observableArray中移除一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完成敲除教程使用列表和集合之后,我决定多花点时间进一步实现带剔除的两级嵌套.

After finishing knockout tutorial working with lists and collections I decided to go a little bit further to implement two level nesting with knockout.

我的ViewModel的结构如下:

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);
    }
}

因此,这类似于可观察数组中的可观察数组.我通过一个简单的2 foreach视图绑定输出它:

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>

问题出在删除语句上(完整的代码在小提琴中).到目前为止,我无法删除该元素.函数仅给我要删除的元素的值,如first,不足以唯一地标识我到底需要删除的内容(是第一个数组中的第一个还是第二个数组中的第一个).

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).

那么有没有办法从observableArray内部的observableArray中正确删除元素?

So is there a way to correctly remove the element from observableArray inside of observableArray?

推荐答案

您可以传递

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) }"/>

然后在您的remove中,您可以通过第二个参数访问父集合,并从其中移除当前元素:

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);
}

演示 JSFiddle .

这篇关于从敲除中的另一个observableArray内部的observableArray中移除一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆