突变观察者-DOM由回调函数更改 [英] Mutation observer - DOM is changed by callback function

查看:61
本文介绍了突变观察者-DOM由回调函数更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法,如何迫使变异观察者忽略由回调函数引起的DOM变化?

is there a way, how to force mutation observer to ignore DOM changes cause by callback function?

现在我有:

var config = { attributes: true, childList: true, characterData: true };
var target = document.body;
var timer;

// create an observer instance
var observer = new MutationObserver(function(mutations) {

   // fired when a mutation occurs
   timer = setTimeout(function () {

      _3rd_party_callback();


   }, 500);  

});

observer.observe(target, config);

问题在于, _3rd_party_callback 回调会导致DOM变化,所以它永远不会停止。顾名思义,它是第三方功能,我无法更改(实际上,操纵DOM是它的目的)。

Problem is that, _3rd_party_callback callback cause DOM change, so it never stops. As its names says, It's third party function and I can't change (actually its DOM manipulating is its purpose).

所以我要做的是断开连接并启动观察器

So what I do is to disconnect and start observer before and after the function is called in callback, respectively.

  observer.disconnect()
  _3rd_party_callback();
  observer.observe(target, config);

这似乎可行,但我担心,由于事件的异步处理,我可能会

It seems to work, but I'm afraid, that thanks to asynchronous handeling of the event I might have observer disabled, when others changes are made and miss them.

不太可能有一种方法将更改与页面本身和回调分开,但我会给出

It's quite unlikely that there's a way to separate changes from page itself and the callback, but I'll give it a try.

推荐答案

只有 observer 可以使您的想法起作用观察目标,仅此而已。这不是一个特别有效的解决方案,因为每次重置可观察对象时您都必须重新设置钩子,但是它将起作用。

Your idea will work if observer will only observe target and nothing else. It's not a particularly efficent solution as you'll have to set up the hooks again each time you reset the observable but it will work.

observer.disconnect()
_3rd_party_callback();
observer.observe(target, config);

您有0次机会错过由 _3rd_party_cb 是由于所有DOM更改都发生在主事件循环中。因此,您断开您的观察者的连接,调用第三方代码,然后重新连接它--- DOM之间没有任何更改的步骤。但是,如果第三方代码推迟更改,例如 setTimeout(messupthedom,0)您仍然会在可观察的范围内获得这些更改。

There is 0 chance that you'll miss an event caused by anything outside of _3rd_party_cb due to all DOM changes occuring in the main event loop. So you disconnect your observer, call the 3rd party code then reconnect it --- there is no step in between for the DOM to change. However if 3rd party code defers a change through, e.g. setTimeout(messupthedom, 0) you'll still pick up these changes in your observable.

这篇关于突变观察者-DOM由回调函数更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆