Is there any existing OnDestroy/OnDispose event in JavaScript or are there any known custom implementations in plain JS or Mootools? Let's say I want to call console.log('bye') when an element gets destroyed/removed from the DOM. Something similar to this jQuery solution
Is there any existing OnDestroy/OnDispose event in JavaScript or are there any known custom implementations in plain JS or Mootools? Let's say I want to call console.log('bye') when an element gets destroyed/removed from the DOM. Something similar to this jQuery solution
Share Improve this question edited May 23, 2017 at 11:52 CommunityBot 11 silver badge asked May 10, 2014 at 16:04 SlavaSlava 3,1074 gold badges35 silver badges41 bronze badges1 Answer
Reset to default 4whereas you can do this, it's not practical to do so.
first - destroy
- the event fill fire with the context of the element that is being destroyed, at which point during the event cb, it will get removed and GCd, potentially.
second, IE6,7,8 where Element prototype is read-only and elements get the methods added to them locally via the $
/document.id
- means that the decorated methods need to be loaded before anything is accessed in the DOM.
third, this won't actually fire if say, el.parentNode.innerHTML = ''
or they get removed via raw js / alternative ways. it's not a true watcher in that sense, just traps 2 methods.
http://jsfiddle/5YYyb/1/
(function(){
// old methods
var destroy = Element.prototype.destroy,
dispose = Element.prototype.dispose;
// redefine them and fire the events before calling old protos.
[Element, Elements].invoke('implement', {
destroy: function(){
this.fireEvent('destroy');
return destroy.apply(this, arguments);
},
dispose: function(){
this.fireEvent('dispose');
return dispose.apply(this, arguments);
}
});
}());
var foo = document.getElement('.foo');
foo.addEvents({
dispose: function(){
alert('we are not in the dom now');
}
});
foo.dispose();
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745077297a4609910.html
评论列表(0条)