我为这个糟糕的标题道歉,但我不知道如何措辞。我有附加到元素的逻辑,并且希望在删除元素时调用类似析构函数的函数。我试过使用 DOMNodeRemoved 作为这个触发器,但是,这不能正常工作,因为:
- DOMNodeRemoved 仅针对元素的父级触发,而不是元素本身。
- 它似乎以特殊的顺序触发,因此有时我无法正确处理该事件。
代码:(或小提琴)
<widget id="widget">
<div>Widget 1</div>
<widget id="widget2">
<div>Widget 2</div>
</widget>
</widget>
<input type="button" value="remove widget" />
Javascript:
var Widget = function(element) {
this.initialize(this.element = element);
};
Widget.prototype = {
initialize: function() {
// does not work for the elements at all
$(this.element).on('DOMNodeRemoved', this.onRemoved.bind(this));
// works, but is not optimal, fired whenever any node is removed.
// DOMNodeRemovedFromDocument doesn't fire for me in latest Chrome
$(this.element).parent().on('DOMNodeRemoved', this.onRemoved.bind(this));
// here is code that adds to a manager
console.log('ADD TO SOME MANAGER', $(this.element).attr('id'));
},
/**
* @private
* Callback for when the element is removed from the DOM
*/
onRemoved: function(ev) {
if (ev.target !== this.element) {
return;
}
this.dispose();
},
/**
* My callback for disposal/destructor
*/
dispose: function() {
// here is code that removes from a manager
console.log('REMOVE FROM SOME MANAGER', $(this.element).attr('id'));
}
};
$(document).ready(function() {
$(this.body).find('widget').each(function(index, element) {
// store widget
$(element).data('widget', new Widget(element));
});
$(this.body).find('input[type=button]').click(function() {
$('#widget').remove();
});
});
上面的代码应该输出:
// ADD TO SOME MANAGER widget
// ADD TO SOME MANAGER widget2
// REMOVE FROM SOME MANAGER widget2 (this should be here but isn't)
// REMOVE FROM SOME MANAGER widget
是否有某种标准用于将逻辑绑定到 jQuery 中的元素?或者我是否必须做某种猴子修补来覆盖“删除”方法(不是首选,因为某些元素可能会被删除而不使用 jquery 的方法)
编辑:我根本不关心 IE。