Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: using native browser events instead of eventemitter3 #1

Open
tjosepo opened this issue Apr 24, 2023 · 1 comment
Open

Comments

@tjosepo
Copy link

tjosepo commented Apr 24, 2023

I'm wondering if the design of the event bus can be simplified by using the browser's native event capabilities.

window.addEventListener(), window.dispatchEvent(), and new CustomEvent() can all be used to achieve a similar API.

Here's a proof-of-concept using them:
https://codesandbox.io/embed/event-based-messaging-slznh4?fontsize=14&hidenavigation=1&theme=dark

Advantages:

  • Simpler implementation.
  • Easier learning curve. Native events and their quirks are already familiar to most front-end developer.
  • No need to manually pass an event bus object around. Just use the window object as the event bus, which is already globally accessible anywhere. This can lead to simpler overall code when using the event bus.
  • No need to use 3rd party library.

Disadvantages:

  • Keys cannot be symbols, they must be strings.

I'm probably missing some things, so let me know what you think of this idea 😄

@patricklafrance
Copy link
Owner

Hey @tjosepo!

Thanks for the suggestion.

Here's my thoughts:

Easier learning curve. Native events and their quirks are already familiar to most front-end developer.

Sadly, I haven't seen many developpers familiar with native events 😆 Most are used to consume them behind a JavaScript library wrapper.

Furthermore, they are not that simple as for backward compatibility reason, there's an overload accepting a bool as the third parameter and another one accepting an object literal:

addEventListener(type, listener, options) vs addEventListener(type, listener, useCapture)

The capture phase is also confusing for most people. Even if it wouldn't matter for a pub/sub usage, it's exposed by the API and must be somewhat understoord to use native events.

Therefore, it would probably still be used behind a wrapper.

It's available everywhere

I think there might be issues with accessing the window object sometimes in Node which could be problematic if we move to SSR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants