Skip to content

Instantly share code, notes, and snippets.

@ayushn21
Created May 31, 2021 13:55
Show Gist options
  • Save ayushn21/5e7c9001fa230538d107db9547691568 to your computer and use it in GitHub Desktop.
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
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