KnockoutJS:如何从子数组中删除项? [英] KnockoutJS : How do I remove an item from a child array?

查看:43
本文介绍了KnockoutJS:如何从子数组中删除项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还在学习knockoutJS,如果我的方法有误,请指导我。

I'm still learning knockoutJS, please guide me if my approach is wrong.

这是我的小提琴: http://jsfiddle.net/amitava82/wMH8J/25/

在onclick编辑时,我收到json模型,它在视图中表示,我想删除某些项目(子数组)或操作(父数组) model(为了简单起见,我删除了添加UI以从小提琴添加更多动作)然后最终将模型传递回服务器。

While onclick of edit, I receive the json model which is represented in the view and I want to remove certain items (child array) or actions (parent array) from the model (I removed add UI to add more Actions from the fiddle for simplicity) and then finally pass the model back to server.

现在,从根级别删除很容易。我坚持在 ActionItems 数组中删除 ActionParamaters 中的单个项目。

Now, deleting from root level is easy. I'm stuck with deleting individual item which is ActionParamaters in ActionItems array.

如何从子数组中删除项?

How do I remove an item from a child array?

推荐答案

你可以通过单击的actionItem和deleteActionItem函数的包含动作数组如下:

You can pass the clicked actionItem and the containing action array to deleteActionItem function as follows:

<!-- /ko -->
<a href="javascript:void(0)" data-bind="click: $root.deleteActionItem.bind($data, $parent)">remove item</a>

在你的模型中,你需要使用ko.mapping插件使每个actionItem数组都可观察(参见编辑功能)

In your model you need to make every actionItem array observable using ko.mapping plugin (see edit function)

var viewModel = function() {
    var self = this;
    self.data = ko.observable();

    self.edit = function() {
       self.data ( ko.mapping.fromJS(editData) );
    }
    self.log = function() {
        console.log(self.data())
    }
    self.deleteAction = function(data) {
       //delete root node
       self.data().remove(data)
    }
    self.deleteActionItem = function(data,actionItem) {
        //delete items
        data.ActionItems.remove(actionItem);
    }
}

然后你就可以从数组中删除该项在deleteActionItem函数中,由于数组现在是可观察的,结果将反映到绑定的dom元素。

Then you will be able to remove the item from array in the deleteActionItem function and since the array is observable now, the result will reflect to binded dom element.

这篇关于KnockoutJS:如何从子数组中删除项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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