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>
disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.
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.
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.
We can use MutationObserver to automatically detect when code snippets are inserted into the page and highlight them.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With