|
Suppose I have a global EventTarget object. For Window and Document, there's |
Answered by
brunnerh
Jun 13, 2026
Replies: 1 comment
|
The main reason to use For a global event bus, an extra component does not really make sense. I would provide a subscription function that takes care of the event listener cleanup, based on the component lifecycle. Along the lines of: const target = new EventTarget();
export function on(type, callback) {
$effect(() => {
target.addEventListener(type, callback);
return () => target.removeEventListener(type, callback);
});
}
export const dispatch = e => target.dispatchEvent(e); |
0 replies
Answer selected by
GulgDev
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The main reason to use
<svelte:window>/<svelte:document>, is the cleanup.Those special elements also make some sense because they actually correspond to an existing element.
For a global event bus, an extra component does not really make sense.
I would provide a subscription function that takes care of the event listener cleanup, based on the component lifecycle. Along the lines of: