Is there a way to simplify this code avoiding to call onDestroy
manually each time?
#10222
Answered
by
Conduitry
frederikhors
asked this question in
Q&A
-
Hi people, thanks for your passion! We're using EventSource in multiple places in out SvelteKit app, like this: <script>
import { onDestroy } from 'svelte';
import { customEventSource } from '$lib/events';
const callback = (event: MessageEvent) => {
console.log('event:', event);
};
customEventSource.addEventListener('message', callback);
onDestroy(() => {
customEventSource.removeEventListener('message', callback);
});
</script> As you can see there is a lot to write each time. Isn't there a magic way - as Svelte has taught us - to simplify? Especially so I don't have to manually call |
Beta Was this translation helpful? Give feedback.
Answered by
Conduitry
Jan 18, 2024
Replies: 1 comment
-
You can encapsulate the Unless you are sure your component will only ever be run in a browser, I would also suggest moving the subscription into an |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
frederikhors
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can encapsulate the
onDestroy
in another module, as in https://svelte.dev/tutorial/ondestroyUnless you are sure your component will only ever be run in a browser, I would also suggest moving the subscription into an
onMount
.