从回调函数中断开Mutation Observer [英] Disconnect Mutation Observer from Callback Function

查看:81
本文介绍了从回调函数中断开Mutation Observer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将变异观察者与其回调函数断开连接?正如他们应该观察到的变化,但我想在第一次变化后断开观察者。由于观察者变量超出范围,因此它不会断开连接。如何将observer变量传递给回调函数,以便代码可以工作?

How can I disconnect my mutation observer from its callback function? The changes are being observed as they should, but I would like to disconnect the observer after the first change. Since the observer variable is out of scope, it's not disconnecting as it should. How can I pass the observer variable to the callback function so the code will work?

function mutate(mutations) {
  mutations.forEach(function(mutation) {
    if ( mutation.type === 'characterData' ) {
      console.log('1st change.');
      observer.disconnect(); // Should disconnect here but observer variable is not defined.
    }
    else if ( mutation.type === 'childList' ) {
      console.log('2nd change. This should not trigger after being disconnected.');
    }
  });
}

jQuery(document).ready(function() {
  setTimeout(function() {
    document.querySelector('div#mainContainer p').innerHTML = 'Some other text.';
  }, 2000);

  setTimeout(function() {
    jQuery('div#mainContainer').append('<div class="insertedDiv">New div!<//div>');
  }, 4000);

  var targetOne = document.querySelector('div#mainContainer');
  var observer = new MutationObserver( mutate );
  var config = { attributes: true, characterData: true, childList: true, subtree: true };

  observer.observe(targetOne, config);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div id="mainContainer">
    <h1>Heading</h1>
    <p>Paragraph.</p>
  </div>
</body>

推荐答案

最简单的方法是调整你的回调

The easiest way would be to adjust your callback

function mutate(mutations) {

function mutate(mutations, observer) {

因为与突变相关的观察者实例会自动传递为变异处理函数的第二个参数。

because the observer instance associated with the mutations is automatically passed as the second parameter to the mutation handler function.

然后你可以在任何需要的时候调用 observer.disconnect()它。

Then you can call observer.disconnect() at whichever time you need it.

这篇关于从回调函数中断开Mutation Observer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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