A type-safe event system with multiple emitter patterns.
The event system is built around individual
Event classes that can be instantiated in isolation,
register and unregister their own listeners, and emit values by executing each listener with
arguments. There are multiple types of events, so choose the best one for each use case.
To begin using events, instantiate an
Event with a unique name -- the name is purely for debugging
Events utilize TypeScript generics for typing the arguments passed to listener functions. This can
be defined using a tuple or an array in the 1st generic slot. The 2nd slot is reserved for
Listeners are simply functions that can be registered to an event using
Event#listen(). The same
listener function reference will only be registered once.
A listener can also be registered to execute only once, using
Event#once(), regardless of how many
times the event has been emitted.
A listener can be unregistered from an event using
Event#unlisten(). The same listener reference
used to register must also be used for unregistering.
To make this flow easier, a pre-configured unlistener is returned from
Emitting is the concept of executing all registered listeners with a set of arguments. This can be
achieved through the
Event#emit() method, which requires an array of values to pass to each
listener as arguments.
The array values and its types should match the generics defined on the constructor.
Scopes are a mechanism for restricting listeners to a unique subset. Scopes are defined as the 2nd
A list of acceptable scope names can be passed as the 2nd generic slot to
Event, otherwise all
strings are allowed.
There are 4 types of events that can be instantiated and emitted.
Standard event that executes listeners in the order they were registered.
Event but can bail the execution loop early if a listener returns
true if a bail occurs.
Executes listeners in parallel and returns a promise with the result of all listeners.
Executes each listener in order, passing the previous listeners return value as an argument to the next listener.
This event only accepts a single argument. The generic type should not be an array, as it types the only argument and the return type.