Last active
November 14, 2016 15:33
-
-
Save syoichi/3366491 to your computer and use it in GitHub Desktop.
nodeObserver - utility function for MutationObserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* example | |
nodeObserver(function log(info) { | |
console.log(info); | |
info.options.observer.disconnect(); | |
}, { | |
target: document, | |
childList: true, | |
subtree: true, | |
addOnly: true | |
}); | |
document.body.appendChild(document.createElement('div')); | |
document.body.insertAdjacentHTML('BeforeEnd', '<div></div><div></div>'); | |
document.body.removeChild(document.body.lastElementChild); | |
setTimeout(function () { | |
document.body.appendChild(document.createElement('div')); | |
}, 1000); | |
// -> log 3 info, not 5 info. | |
*/ | |
/** | |
* utility function for MutationObserver | |
* @version 3.0.0 | |
* @link https://dom.spec.whatwg.org/#mutation-observers | |
* @param {Function} callback | |
* @param {Object} options | |
* @returns {Object} options | |
*/ | |
function nodeObserver(callback, options) { | |
let hasOnly = options.addOnly || options.removeOnly; | |
let nodesType = options.addOnly ? 'addedNodes' : 'removedNodes'; | |
let observer = new MutationObserver(mutations => { | |
for (let record of mutations) { | |
let nodes = record.type === 'childList' && hasOnly ? | |
record[nodesType] : | |
[null]; | |
for (let node of nodes) { | |
callback({node, record, options}); | |
} | |
} | |
}); | |
observer.observe(options.target, options); | |
return Object.assign(options, {observer, callback}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment