Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disconnect Mutation Observer from Callback Function

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>
like image 594
GTS Joe Avatar asked Dec 25 '16 19:12

GTS Joe


People also ask

How do you get rid of mutation in Observer?

disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.

Is mutation observer async?

The answer here is that MutationObserver works asynchronously. For example, if you change three items in the DOM at the same time — the subscriber will be called only once, but with three mutations, and each will represent each change you made.

What is MutationObserver in Javascript?

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

When would you use a mutation observer?

We can use MutationObserver to automatically detect when code snippets are inserted into the page and highlight them.


1 Answers

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.

like image 169
loganfsmyth Avatar answered Sep 21 '22 11:09

loganfsmyth