Skip to content

Instantly share code, notes, and snippets.

@rufus2021
Created January 16, 2016 04:41
Show Gist options
  • Save rufus2021/91c0443fa8bfee2a3cd5 to your computer and use it in GitHub Desktop.
Save rufus2021/91c0443fa8bfee2a3cd5 to your computer and use it in GitHub Desktop.
var div = document.getElementById('div');
var observer = new MutationObserver(cb);
var config = { attributes: true, attributeOldValue: true, childList: true };
// observe a target
observer.observe(div, config);
// perform some actions on that target which creates a record queue
var child = document.createElement('span');
child.textContent = 'hi there!';
div.appendChild(child); // creates a mutation record and adds to queue. now we have a queue of length 1
div.classList.toggle('active'); // creates a mutation record and adds to queue. now we have a queue of length 2
// by this point we have two records in the queue
// mutation callback fires after all other code finishes.
// in this case, takeRecords() fires first and empties the queue, so this won't ever run
// but if you try takeRecords() after this runs there won't be a record queue which is why it was coming back empty.
// try it by commenting out line 28
function cb(mutations, instance) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
}
console.log('I run before function cb (){}');
// empties the queue making cb useless
console.log('records ', observer.takeRecords());
TLDR; seems takeRecords isn't useful unless not all mutations are acted upon. but i didn't test that case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment