Created
May 31, 2021 13:55
-
-
Save ayushn21/5e7c9001fa230538d107db9547691568 to your computer and use it in GitHub Desktop.
A wrapper around MutationObserver to observe an element's tree for nodes matching a selector being added or removed
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
export class ElementObserver { | |
constructor(element, selector, delegate) { | |
this.element = element | |
this.selector = selector | |
this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations)) | |
this.delegate = delegate | |
} | |
start() { | |
this.mutationObserver.observe(this.element, { childList: true, subtree: true }) | |
} | |
refresh() { | |
this.matchSelectorInTree(this.element, element => { | |
this.delegate?.selectorMatched(element) | |
}) | |
} | |
processMutations(mutations) { | |
for (const mutation of mutations) { | |
this.processRemovedNodes(mutation.removedNodes) | |
this.processAddedNodes(mutation.addedNodes) | |
} | |
} | |
processAddedNodes(nodes) { | |
for (const node of Array.from(nodes)) { | |
if (node.nodeType == Node.ELEMENT_NODE) { | |
this.matchSelectorInTree(node, element => { | |
this.delegate?.selectorMatched(element) | |
}) | |
} | |
} | |
} | |
processRemovedNodes(nodes) { | |
for (const node of Array.from(nodes)) { | |
if (node.nodeType == Node.ELEMENT_NODE) { | |
this.matchSelectorInTree(node, element => { | |
this.delegate?.matchedSelectorRemoved(element) | |
}) | |
} | |
} | |
} | |
matchSelectorInTree(tree, callback) { | |
return tree.querySelectorAll(this.selector).forEach(element => { | |
callback(element) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment