Search code examples
javascriptcallbackmutation-observers

Mutation Observer with External Callback Function Code


I am trying to rewrite the following Mutation Observer code:

var target = document.querySelector('div#cart');

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation.type);
    });
});

var config = { childList: true, attributes: true, characterData: true, subtree: true };
observer.observe(target, config);

Into the script below:

var target = document.querySelector('div#cart'), observer, moCallback, config;

moCallback = function(mutations) {
    mutations.forEach( mutation ) {
        console.log(mutation.type);
    }
};

var array = moCallback;

observer = new MutationObserver( array );

config = { childList: true, attributes: true, characterData: true, subtree: true };
observer.observe(target, config);

The second script is easier for me to read since it doesn't have the embedded callback function; however, I can't get it to work.

How can I rewrite my Mutation Observer with an external callback function instead of an inline anonymous function?


Solution

  • Here is a working example:

    /*
    if you run this script on this page, you will see that it works as expected.
    */
    var target = document.getElementById('header'); // This is the area you're watching for changes. If it's not working, increase the scope (go up the selector cascade to parent elements).
    var observer = new MutationObserver(mutate);
    
    function mutate(mutations) {
        mutations.forEach(function(mutation) { // When the main image changes...
            console.log(mutation.type);
        });
    }
    
    var config = { childList: true, attributes: true, characterData: true, subtree: true };
    observer.observe(target, config);
    setTimeout(function(){
      target.className = "some class";
    },2000);