jQuery 事件未在 "cleaning" 敲除绑定后触发
jQuery events not firing after "cleaning" Knockout bindings
在我的项目中,我有一个 <div>
专门应用我的 Knockout.js 绑定。我必须根据用户点击的内容在该区域实例化不同的视图模型。
为了防止出现 无法在同一元素上调用绑定两次 错误,我首先必须 "Clean" 绑定以使该区域再次可用。我调用初始 applyBindings()
函数:
ko.applyBindings(new ViewModel("Planet", "Earth"), document.getElementById("bindings-area"));
最终,我将清理 <div>
并调用新绑定:
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()
对按钮进行操作?
Fiddle: http://jsfiddle.net/jL6L01xs/2/
这个问题在 Knockout documentation 中有很好的描述。这句话描述了问题是什么以及需要做什么:
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。
在我的项目中,我有一个 <div>
专门应用我的 Knockout.js 绑定。我必须根据用户点击的内容在该区域实例化不同的视图模型。
为了防止出现 无法在同一元素上调用绑定两次 错误,我首先必须 "Clean" 绑定以使该区域再次可用。我调用初始 applyBindings()
函数:
ko.applyBindings(new ViewModel("Planet", "Earth"), document.getElementById("bindings-area"));
最终,我将清理 <div>
并调用新绑定:
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()
对按钮进行操作?
Fiddle: http://jsfiddle.net/jL6L01xs/2/
这个问题在 Knockout documentation 中有很好的描述。这句话描述了问题是什么以及需要做什么:
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 preventcleanData
from being called, an empty function could be used to replace the standardcleanExternalData
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。