简体   繁体   中英

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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM