Skip to content

Instantly share code, notes, and snippets.

@ayamomiji
Created October 16, 2020 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayamomiji/7809dd51915a80fe93aeb452d7f16662 to your computer and use it in GitHub Desktop.
Save ayamomiji/7809dd51915a80fe93aeb452d7f16662 to your computer and use it in GitHub Desktop.
componentWillUnmount/beforeDestroy in alpine.js
<div x-data @remove='console.log($el, "removed")'></div>
const observer = new MutationObserver(mutations => {
for (const mutation of mutations) {
if (mutation.type !== 'childList') continue
mutation.removedNodes.forEach(node => {
if (node.nodeType !== Node.ELEMENT_NODE) return
[node, ...node.querySelectorAll('[\\@remove]')].forEach(node => {
node.dispatchEvent(new CustomEvent('remove'))
})
})
}
})
observer.observe(document, {
childList: true,
subtree: true
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment