断开 Mutation Observer 与回调函数的连接

Disconnect Mutation Observer from Callback Function

如何断开变异观察器与其回调函数的连接?正在按应有的方式观察更改,但我想在第一次更改后断开观察者的连接。由于 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);
});
<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>

最简单的方法是调整回调

function mutate(mutations) {

function mutate(mutations, observer) {

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

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