【问题标题】:Mutation Observer with External Callback Function Code带有外部回调函数代码的突变观察者
【发布时间】:2017-03-01 11:21:55
【问题描述】:

我正在尝试重写以下 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?

【问题讨论】:

  • 您的 forEach 在您的第二个脚本中搞砸了,更改它以使其与 script1 中的相匹配。
  • 我更新了 forEach() 循环,但语法仍然混乱。可以通过外部回调调用 Mutation Observer 吗?如果是,我还没有在网上找到可以遵循的示例。
  • 回调函数不需要内联定义。

标签: javascript callback mutation-observers


【解决方案1】:

这是一个工作示例:

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

【讨论】:

  • 这正是我想要的。非常感谢你,尼克!
  • 太棒了。没问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-20
  • 1970-01-01
  • 2012-08-04
  • 2016-08-26
  • 2018-06-15
相关资源
最近更新 更多