最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to implement OnDestroyOnDispose event in JSMootools? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 4

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/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();
发布评论

评论列表(0)

  1. 暂无评论