Disconnect Mutation Observer from Callback Function

9.7k views Asked by At

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>

1

There are 1 answers

9
loganfsmyth On BEST ANSWER

The easiest way would be to adjust your callback

function mutate(mutations) {

to

function mutate(mutations, observer) {

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

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