Question

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

Was it helpful?

Solution

whereas 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.net/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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top