Reputation: 25
I'm studying Svelte JS. In this REPL and wonder to know what is the purpose of the onDestroy
method added in the definition of the component Tabs
. I understand that it is the way to manage what happens when a component is destroyed but I've never seen it defined inside another method.
tab => {
tabs.push(tab);
selectedTab.update(current => current || tab);
onDestroy(() => {
const i = tabs.indexOf(tab);
tabs.splice(i, 1);
selectedTab.update(current => current === tab ? (tabs[i] || tabs[tabs.length - 1]) : current);
});
},
Upvotes: 1
Views: 2504
Reputation: 25001
There is one simple rule with lifecycle functions like onDestroy
: they have to be called during component init, that is they must be called synchronously in the component's <script>
tag.
<script>
import { onDestroy } from 'svelte'
onDestroy(..) // ok
{
onDestroy(..) // ok
}
(() => {
onDestroy(..) // ok
})()
const fn = callback => {
onDestroy(callback)
}
fn() // ok
setTimeout(() => {
onDestroy(..) // NOT OK !!!
fn() // NOT OK
})
</script>
What's important is when the call is made, not where in the code it is located. The lifecycle callback will be attached to the component currently being initialized, wherever the call comes from.
You can put onDestroy
in a function if you want, that just means that the user of this function will have to call it during the init of a component, and the callback will run when this component is destroyed.
In the example you've linked, the context is used as a transport for the function that contains onDestroy
. Context also have to be resolved synchronously during the init phase of a component, so we're good. The component gets the function from the context, it calls it immediately, and the function can register some cleanup on the component without the component knowing. That's nice encapsulation.
Upvotes: 3
Reputation: 114787
Calling onDestroy
adds a callback that will be called when the svelte component is destroyed. You can add as many callbacks as you want and call the method whenever you want.
Here, it looks like the developer wanted different cleanup routines for different contexts.
Upvotes: 0