简体   繁体   English

MutationObserver在callback函数内调用disconnect()调用

[英]MutationObserver disconnect() call inside callback function

I'm using MutationObserver to wait the creation of an element on the page, and then adding a button on it (with init function). 我正在使用MutationObserver等待页面上的元素创建,然后在其上添加一个按钮(使用init函数)。 But I only need to add one button, and mutations keep happening after this. 但是我只需要添加一个按钮,之后突变就会继续发生。 I would like to disconnect() the observer after having added this button. 我想在添加此按钮后disconnect()观察者。

I tried something like this : 我试过这样的事情:

function detect_node_for_buttons(mutations){
    var selector = 'div[class="_2o3t fixed_elem"]';
    mutations.forEach(function (mutation){
        var element =   $(document).find(selector);
        if (element){
            init();
            observer.disconnect();
            return;
        }
        if (!mutation.addedNodes) return;
        for (var i = 0; i < mutation.addedNodes.length; i++){
            if (mutation.addedNodes[i].matches(selector)){
                init();
                observer.disconnect();
            }
        }
    });
}

var observer = new MutationObserver(function (mutations){
    detect_node_for_buttons(mutations);
});

But it didn't work (Perhaps because observer isn't yet defined when I call observer.disconnect() in detect_node_for_buttons() )? 但它不起作用(也许是因为我在detect_node_for_buttons()中调用observer.disconnect() 时尚未定义 观察者 )?

How could I do? 我该怎么办?

Callback function in MutationObserver is called with two arguments: mutations array and observer object itself. MutationObserver回调函数使用两个参数调用:mutation数组和observer对象本身。 Because of how you wrote the code detect_node_for_buttons never gets observer object. 由于您编写代码的方式, detect_node_for_buttons永远不会获得观察者对象。 This will do the trick: 这样就可以了:

var observer = new MutationObserver(detect_node_for_buttons);

You also have to add this argument to function declaration: 您还必须将此参数添加到函数声明中:

function detect_node_for_buttons(mutations, observer){ ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM