ev-pubsub
asynchronous publish/subscribe module.
npm is flooded with similar modules but I couldn't find any that satisfy all of these criteria:
- doesn't generate memory garbage
- favors factory pattern over terrible javascript classes
- events published in next event loop tick
- works in both commonjs (require) and es modules (import)
- simple (< 100 lines of code)
so, here we are.
including
// *OR* const pubsub = // commonjs (node) approach
basic usage
const a = a a // all arguments after the first will be sent to subscribersa /*prints: hello from 1: val ahello from 2: val b*/
event loop considerations
many pubsub implementations immediately invoke published events.
A problem with this approach is you might end up missing events if they happen before subscribing to them.
ev-pubsub
gets around this by invoking published events in the next event tick (asynchronously.) example:
{ console} const mine = mine mine /*prints: event message: omg it happened!*/
In some libraries you might expect this to print nothing, because you didnt subscribe to the
some-event
event until after it was published to. Because this library publishes events on the
next tick, you'll be able to set up subscribers without worrying about losing messages due to ordering.
unsubscribe
You may also unregister event handlers if you need to cleanup or prevent memory leaks:
{ console} const a = a a // simulate some time passing /*prints: yo! zero arg one arg*/
unsubscribe all handlers for a given topic
{ console} { console} const a = a a a a consolea /*prints: yo! ayyyo2! ayyunsubscribed all...*/
once
You may want to only subscribe to one event:
{ console} const a = a aa /*prints: yo! 15*/