在 KnockoutJS 中触发 beforeRemove、afterAdd 处理程序
我在触发 KnockoutJs beforeRemove 和 afterAdd 处理程序时遇到一些问题。
这是相关的代码片段
function viewModel(list) {
var self = this;
this.items = ko.observableArray(list);
this.removeItem = function(item) {
self.items.remove(item);
}
this.removeFirst = function() {
self.removeItem(self.items()[0]);
};
this.onRemove = function(elements) {
console.log("Updating");
$(elements).addClass('transition-out');
};
}
ko.applyBindings(new viewModel(items));
这个标记
<button data-bind="click: removeFirst">Remove first</button>
<ul data-bind='foreach: items, beforeRemove: onRemove'>
<li data-bind="text: name, click: $parent.removeItem"></li>
</ul>
,我看到
列表更新,但 onRemove
处理程序从未被触发。我创建了一个 JSFiddle 来说明问题。
谢谢,
吉恩
I am having some problems getting KnockoutJs beforeRemove and afterAdd handlers to fire.
This is the relevant code fragment
function viewModel(list) {
var self = this;
this.items = ko.observableArray(list);
this.removeItem = function(item) {
self.items.remove(item);
}
this.removeFirst = function() {
self.removeItem(self.items()[0]);
};
this.onRemove = function(elements) {
console.log("Updating");
$(elements).addClass('transition-out');
};
}
ko.applyBindings(new viewModel(items));
And this markup
<button data-bind="click: removeFirst">Remove first</button>
<ul data-bind='foreach: items, beforeRemove: onRemove'>
<li data-bind="text: name, click: $parent.removeItem"></li>
</ul>
I am seeing list updates but the onRemove
handler is never fired.
I've created a JSFiddle to illustrate the problem.
Thanks,
Gene
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要使用的语法如下所示:
beforeRemove
是foreach
(最终是template
)绑定接受的选项。它按照您指定的方式被视为单独的绑定。如果绑定不存在,则会忽略它(某些绑定是通过 allBindingsAccessor 访问的,因此 KO 不会知道这一点,也不会抛出错误)。此外,该函数将为“模板”中的每个节点调用一次。在您的情况下,它将是一个文本节点、
li
和另一个文本节点。如果要忽略文本节点,请检查元素的(第一个参数)nodeType 是否为 1。The syntax that you want to use looks like:
beforeRemove
is an option that is accepted by theforeach
(and ultimately thetemplate
) binding. It was being treated as a separate binding in the way that you were specifying it. If a binding does not exist, then it is ignored (some binding are accessed via allBindingsAccessor, so KO wouldn't know that and doesn't throw an error).Also, the function will get called once for each node in your "template". In your case it will be a text node, the
li
, and another text node. If you want to ignore the text nodes, then check that the element's (first argument) nodeType is 1.