Add lifecycle directive x-destroy
or x-disconnected
or x-unmounted
#2218
Replies: 4 comments 5 replies
-
It's undocumented but if you add a function called destroy to x-data, it gets called when a component is removed from the dom. |
Beta Was this translation helpful? Give feedback.
-
I think it’s undocumented, but just like the init() function, you can set a destroy() function to do things after the element gets removed. It’s on this line: |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
As noted in #2103, the FWIW, here's a custom directive I'm using to accomplish this: Alpine.directive('cleanup', (_el, { expression }, { evaluate, cleanup }) => {
cleanup(() => {
evaluate(expression)
})
}) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi there, just started looking into alpinejs today. I'm impressed! One thing I'm missing would be a way to execute some code every time an element with
x-data
attached to it is being removed from the DOM. Think "the opposite ofx-init
".In standard web custom elements this would be the
disconnectedCallback
, as described on MDN under Lifecycle Callbacks. The Vue version would beunmounted
(https://v3.vuejs.org/api/options-lifecycle-hooks.html#unmounted).I saw something about a
cleanup
function on the Alpinejs Docs under Custom Directives – so the functionality seems to be there. It would be amazing if it could be made as easily accessible as theinit()
directive.Beta Was this translation helpful? Give feedback.
All reactions