DOMNodeRemovedFromDocument的简单MutationObserver版本 [英] simple MutationObserver version of DOMNodeRemovedFromDocument

查看:117
本文介绍了DOMNodeRemovedFromDocument的简单MutationObserver版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为DOM元素附加了一些功能,并且希望能够在从DOM中删除该元素时清除所有引用,以便可以对其进行垃圾回收。

I attach some functionality to DOM elements and want to be able to clear all references when the element is removed from the DOM so it can be garbage collected,

我的用于检测元素的去除的初始版本是这样的:

My initial version to detect the removel of an element was this:

var onremove = function(element, callback) {
    var destroy = function() {
        callback();
        element.removeEventListener('DOMNodeRemovedFromDocument', destroy);
     };
     element.addEventListener('DOMNodeRemovedFromDocument', destroy);
};

然后我读到变异事件,而推荐使用 MutationObserver 。所以我试图移植我的代码。这是我想出的:

Then I read that mutation events were deprecated in favor of MutationObserver. So I tried to port my code. This is what I came up with:

 var isDescendant = function(desc, root) {
     return !!desc && (desc === root || isDecendant(desc.parentNode, root));
 };

var onremove = function(element, callback) {
    var observer = new MutationObserver(function(mutations) {
        _.forEach(mutations, function(mutation) {
            _.forEach(mutation.removedNodes, function(removed) {
                if (isDescendant(element, removed)) {
                    callback();

                    // allow garbage collection
                    observer.disconnect();
                    observer = undefined;
                }
            });
        });
    });
    observer.observe(document, {
         childList: true,
         subtree: true
    });
};

对我来说,这看起来过于复杂(而且效率不高)。我是否丢失了某些东西,或者这真的是应该使用的方式吗?

This looks overly complicated to me (and not very efficient). Am I missing something or is this really the way this is supposed to work?

推荐答案

实际上...是的,有一个

Actually... yes, there is a more elegant solution :).

您添加的内容看起来不错,而且似乎已经优化。但是,有一种更简单的方法来知道节点是否已连接到DOM。

What you added looks good and seems to be well optimized. However there is an easier way to know if the node is attached to the DOM or not.

function onRemove(element, onDetachCallback) {
    const observer = new MutationObserver(function () {
        function isDetached(el) {
            if (el.parentNode === document) {
                return false;
            } else if (el.parentNode === null) {
                return true;
            } else {
                return isDetached(el.parentNode);
            }
        }

        if (isDetached(element)) {
            observer.disconnect();
            onDetachCallback();
        }
    })

    observer.observe(document, {
         childList: true,
         subtree: true
    });
}

这篇关于DOMNodeRemovedFromDocument的简单MutationObserver版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆