简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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