Skip to content
Discussion options

You must be logged in to vote

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:

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);

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by GulgDev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants