从回调函数中断开Mutation Observer

时间:2016-12-25 19:24:20

标签: javascript disconnect mutation-observers

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



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);
});
&#13;
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:10)

最简单的方法是调整回调

function mutate(mutations) {

function mutate(mutations, observer) {

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

然后,您可以在任何需要的时候致电observer.disconnect()