prototype - Trigger event when an element is removed from the DOM

 ̄綄美尐妖づ 提交于 2020-01-04 05:25:22

问题


I'm trying to figure out how to execute some js code when an element is removed from the page:

Something in prototype like:

$('custom-div').observe('remove', function(event) {
    // Handle the event
});

Does anything like this exist?


回答1:


In modern browsers, you can use a MutationObserver. Here's code that will call a callback when a DOM element is removed from it's current location:

function watchRemove(el, fn) {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            var item;
            if (mutation.type === "childList" && mutation.removedNodes) {
                for (var i = 0; i < mutation.removedNodes.length; i++) {
                    item = mutation.removedNodes[i];
                    if (item === el) {
                        // clear the observer
                        observer.disconnect();
                        fn.call(item, item);
                        break;
                    }
                }
            }
      });    
    });
    observer.observe(el.parentNode, {childList: true});
    return observer;
}

And, a working demo: http://jsfiddle.net/jfriend00/naft3qeb/

This watches the parent for changes to its direct children and calls the callback if the specific DOM element passed in is removed.

The observer will remove itself when the DOM element is removed or watchRemove() returns the observer instance which you can call .disconnect() on at any time to stop the watching.

Here's a jQuery plug-in that uses this functionality:

jQuery.fn.watchRemove = function(fn, observers) {
    return this.each(function() {
        var o = watchRemove(this, fn);
        if (observers) {
            observers.push(o);
        }
    });
}

In this case, it accepts an optional array object as an argument that will be filled with all the observer objects (only necessary to pass this if you want to be able to stop the watching yourself on any given item).



来源:https://stackoverflow.com/questions/33312948/prototype-trigger-event-when-an-element-is-removed-from-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!