我为糟糕的头衔道歉,但我不确定如何说出来。我有附加到元素的逻辑,并且想要在删除元素时调用类似析构函数的函数。我已尝试使用DOMNodeRemoved作为此触发器,但是,这不能正常工作,因为:
代码:(或fiddle)
<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。
答案 0 :(得分:4)
jQuery UI对cleanData内部jQuery方法进行了内置更改,该方法触发了remove事件。如果将其实现到代码中,则可以使用它来解决问题。
var _cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
现在只要使用jQuery方法(例如.empty()
,.remove()
或.html()
)删除元素,就可以使用remove事件。 http://jsfiddle.net/2dwbk/
当然,如果你有jQuery UI,你根本不需要上面的代码,只需绑定到remove事件。