[英]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? 如何使用外部回调函数而不是嵌入式匿名函数重写Mutation Observer?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.