vmonteco
vmonteco

Reputation: 15393

How to disconnect a MutationObserver from inside its callback function?

I'm using MutationObserver to wait for the creation of an element on the page, and then adding a button on it (with init function).

I only need to add one button but mutations keep happening after this. I would like to disconnect() the observer after having added this button.

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())?

How could I do it?

Upvotes: 5

Views: 3878

Answers (1)

Tithen-Firion
Tithen-Firion

Reputation: 625

Callback function in MutationObserver is called with two arguments: mutations array and observer object itself. Because of how you wrote the code detect_node_for_buttons never gets observer object. 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){ ... }

Upvotes: 11

Related Questions