项目已从 Knockout 可观察数组中删除,但未从 html 表中删除 [英] Item removed from Knockout observable array, but not from html table

查看:21
本文介绍了项目已从 Knockout 可观察数组中删除,但未从 html 表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 plunk 来证明我的问题:http://plnkr.co/edit/PzBrcTX0Vnn01xWy4dk6

I have a plunk that demonstrates my issue: http://plnkr.co/edit/PzBrcTX0Vnn01xWy4dk6

这是一个包含设置"列表的表格.它使用 Footable,因此可以对列表进行排序以及 Footable 的其他功能.

This is a table that has a list of "settings". It uses Footable so the list can be sorted and other features of Footable.

场景一:运行,为一行或多行按下删除设置按钮.请注意,按下按钮后该行被删除.这是预期的行为.

Scenario 1: run, push the remove setting button for one or more rows. Notice that the row is removed after the buttons is pushed. This is the expected behavior.

场景二:运行,点击设置列标题并确保该列已排序,按下移除按钮.请注意,该行并未从视图中删除.

Scenario 2: run, click on the setting column header and ensure that the column is sorted, push the remove button. Notice that the row is not removed from the view.

如果你在 ApplicationSettings.js 中放置一个断点:

If you put a break point in ApplicationSettings.js:

var removeItem = function (item) {
    items.remove(item);
};

您可以看到,在两种情况下,可观察数组都按预期删除了项目,但在情况 2 中,视图未按预期更新.

You can see that in both scenarios the observable array is removing the items as expected, but in scenario 2 the view is not updated as expected.

推荐答案

问题来自于围绕每个 元素的空文本节点.foreach 绑定也跟踪这些文本节点.请参阅 https://github.com/knockout/knockout/pull/709 进行讨论关于为什么不能将它们作为一般规则忽略的原因.另一方面,您的自定义绑定可以去除它们.

The issue comes from the empty text nodes that surround each <tr> element. The foreach binding also tracks those text nodes. See https://github.com/knockout/knockout/pull/709 for a discussion about why it's not possible to just ignore them as a general rule. On the other hand, your custom binding can strip them out.

了解如何k/a> 这样做(出于类似的原因):

See how knockout-sortable does this (for similar reasons):

var nodes = Array.prototype.slice.call(element.childNodes, 0);
ko.utils.arrayForEach(nodes, function(node) {
    if (node && node.nodeType !== 1) {
        node.parentNode.removeChild(node);
    }
});

您需要确保它在 foreach 之前运行.我修改了你的绑定来做到这一点:http://plnkr.co/edit/hS6Gb2xLfabSj9K8l03y?p=preview

You need to make sure this is run before foreach. I modified your binding to do that: http://plnkr.co/edit/hS6Gb2xLfabSj9K8l03y?p=preview

这篇关于项目已从 Knockout 可观察数组中删除,但未从 html 表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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