我正在尝试重写以下Mutation Observer代码:
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);
进入下面的脚本:
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);
第二个脚本对我来说更容易阅读,因为它没有嵌入式回调函数;但是,我无法让它发挥作用。
如何使用外部回调函数而不是内联匿名函数重写Mutation Observer?
答案 0 :(得分:2)
这是一个有效的例子:
/*
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);