jQuery事件在“清理"后不会触发敲除绑定 [英] jQuery events not firing after "cleaning" Knockout bindings

查看:108
本文介绍了jQuery事件在“清理"后不会触发敲除绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有一个<div>,我专门在其中应用Knockout.js绑定.我必须根据用户单击的内容在该区域实例化不同的视图模型.

In my project, I have an <div> where I specifically apply my Knockout.js bindings. I have to instantiate different viewmodels in that area depending on what the user clicks.

为防止在同一元素上两次出现不能两次调用绑定错误,我首先必须清理"绑定以使该区域再次可用.我调用了初始的applyBindings()函数:

To prevent getting a cannot call bindings twice on the same element error, I first have to "Clean" the bindings to make the area available again. I call the initial applyBindings() function:

ko.applyBindings(new ViewModel("Planet", "Earth"), document.getElementById("bindings-area"));

最终,我将清理<div>并调用新的绑定:

Eventually, I will clean the <div> and call the new bindings:

var element = $("#bindings-area")[0];
ko.cleanNode(element);
ko.applyBindings(new ViewModel("NEW", "Bindings"), document.getElementById("bindings-area"));

问题::当我在#bindings-area div中包含HTML按钮时,在清除绑定并实例化新模型后,该按钮将不再起作用.我敢肯定它与ko.cleanNode()函数有关,并且还以某种方式删除了 button 绑定.我该如何重新启动它们或首先阻止cleanNode()在按钮上进行操作?

Problem: When I include an HTML button in the #bindings-area div, it will no longer work after I clean the bindings and instantiate the new model. I'm sure it has to do with the ko.cleanNode() function somehow removing the button bindings as well. How can I re-initiate them or prevent cleanNode() from operating on the button in the first place?

提琴手: http://jsfiddle.net/jL6L01xs/2/

推荐答案

淘汰文件.这句话描述了问题所在以及需要做什么:

This issue is nicely described in Knockout documentation. This quote describes what the issue is and what needs to be done:

在删除元素时,淘汰赛会运行逻辑以清理所有数据 与元素关联.作为此逻辑的一部分,淘汰赛呼叫 jQuery的cleanData方法(如果在页面中加载了jQuery).在 高级方案,您可能要阻止或自定义此数据的方式 已在您的应用程序中删除.淘汰赛展示了一个功能, ko.utils.domNodeDisposal.cleanExternalData(node),可以是 重写以支持自定义逻辑.例如,为防止cleanData 从被调用,一个空函数可以用来代替 标准cleanExternalData实现:

When removing an element, Knockout runs logic to clean up any data associated with the element. As part of this logic, Knockout calls jQuery’s cleanData method if jQuery is loaded in your page. In advanced scenarios, you may want to prevent or customize how this data is removed in your application. Knockout exposes a function, ko.utils.domNodeDisposal.cleanExternalData(node), that can be overridden to support custom logic. For example, to prevent cleanData from being called, an empty function could be used to replace the standard cleanExternalData implementation:

ko.utils.domNodeDisposal.cleanExternalData = function () {
    // Do nothing. Now any jQuery data associated with elements will
    // not be cleaned up when the elements are removed from the DOM.
};

这是更新的 jsFiddle .

这篇关于jQuery事件在“清理"后不会触发敲除绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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