简体   繁体   English

突变观察者-DOM由回调函数更改

[英]Mutation observer - DOM is changed by callback function

is there a way, how to force mutation observer to ignore DOM changes cause by callback function? 有没有一种方法,如何迫使变异观察者忽略回调函数引起的DOM变化?

Right now I have: 现在我有:

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

Problem is that, _3rd_party_callback callback cause DOM change, so it never stops. 问题是, _3rd_party_callback回调导致DOM更改,因此它永远不会停止。 As its names says, It's third party function and I can't change (actually its DOM manipulating is its purpose). 顾名思义,它是第三方功能,我无法更改(实际上,它的DOM操作是其目的)。

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. 很难将页面本身和回调中的更改分开,但是我将尝试一下。

Your idea will work if observer will only observe target and nothing else. 如果observerobserve目标observe其他东西,那么您的想法将起作用。 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);

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. 由于主事件循环中发生了所有DOM更改,因此您有0个机会错过由_3rd_party_cb以外的任何内容引起的事件。 So you disconnect your observer, call the 3rd party code then reconnect it --- there is no step in between for the DOM to change. 因此,您断开了与观察者的连接,调用了第三方代码,然后重新连接它--- DOM之间没有任何更改的步骤。 However if 3rd party code defers a change through, eg setTimeout(messupthedom, 0) you'll still pick up these changes in your observable. 但是,如果第三方代码通过setTimeout(messupthedom, 0)推迟更改,您仍将在可观察范围内接受这些更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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