Are listeners like <svelte:window on:keydown={handleKeydown}/> component scoped or global?

Viewed 1712

If I add a key listener inside a component using

<svelte:window on:keydown={handleKeydown}/>

as per https://svelte.dev/tutorial/svelte-window , is the listener removed when the component is destroyed? I want to be sure I am not causing memory leaks of any kind.

1 Answers

Yes, if you want, you can look at the generated JS code and you will find this:

m(target, anchor) {
    dispose = listen(window, "keydown", /*handleKeydown*/ ctx[0]);
},
...
...
d(detaching) {
    dispose();
}

The m() method is the mounting function and the d() is the destroy. You can see the listener is added in the m() and then it is removed in the d(). This is simplified but you can find out more by investigating the Svelte source code :)

Good luck!

Related