You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
A type-safe marriage ofEventTarget andEventEmitter.
Features
🎯Event-based. Control event flow: prevent defaults, stop propagation, cancel events. Something your commonEmitter can't do.
🗼Emitter-inspired. Emit event types and data, don't bother with creatingEvent instances. A bit less verbosity than a commonEventTarget.
⛑️Type-safe. Describe the exact event types and payloads accepted by the emitter. Never emit or listen to unknown events.
🧰Convenience methods like.emitAsPromise() and.emitAsGenerator() to build more complex event-driven systems.
🐙Tiny. 700B gzipped.
Warning
This librarydoes not have performance as the end goal. In fact, since it operates on events and supports event cancellation, it will likely beslower than the emitters that don't do that.
Motivation
Why not justEventTarget?
TheEventTarget API is fantastic. It works in the browser and in Node.js, dispatches actual events, supports cancellation, etc. At the same time, it has a number of flaws that prevent me from using it for anything serious:
Complete lack of type safety. Thetype innew Event(type) is not a type argument inlib.dom.ts. It's alwaysstring. It means it's impossible to narrow it down to a literal string type to achieve type safety.
No concept of.prependListener(). There is no way to add a listener to runfirst, before other existing listeners.
No concept of.removeAllListeners(). You have to remove each individual listener by hand. Good if you own the listeners, not so good if you don't.
No concept of.listenerCount() or knowing if a dispatched event had any listeners (theboolean returned from.dispatch() indicates if the event has been prevented, not whether it had any listeners).
(Opinionated) Verbose. I prefer.on() over.addEventListener(). I prefer passing data than constructingnew MessageEvent() all the time.
Why not justEmitter (in Node.js)?
TheEmitter API in Node.js is great, but it has its own downsides:
Node.js-specific.Emitter does not work in the browser.
Lacks any type safety.
No concept of.stopPropagation() and.stopImmediatePropagation(). Those methods are defined but literally do nothing.
Install
npm install rettime
API
TypedEvent
TypedEvent is a subset ofMessageEvent that allows for type-safe event declaration.
TheEventMap type argument allows you describe the supported event types, their payload, and the return type of their event listeners.
import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<string,number>}>()emitter.on('hello',()=>1)// ✅emitter.on('hello',()=>'oops')// ❌ string not assignable to type numberemitter.emit(newTypedEvent('hello',{data:'John'}))// ✅emitter.emit(newTypedEvent('hello',{data:123}))// ❌ number is not assignable to type stringemitter.emit(newTypedEvent('hello'))// ❌ missing data argument of type stringemitter.emit(newTypedEvent('unknown'))// ❌ "unknown" does not satisfy "hello"
Describing events
TheEmitter class requires a type argument that describes the event map. If you do not provide that argument, adding listeners or emitting events will produce a type error as your emitter doesn't have an event map defined.
An event map is an object of the following shape:
{[type:string]:TypedEvent}
Thetype is a string indicating the event type (e.g.greet orping). The array it accepts has two members:args describes the arguments accepted by this event (can also benever for events without arguments) andreturnValue is an optional type for the data returned from the listeners for this event.
Let's say you want to define agreet event that expects a user name as data and returns a greeting string:
When providing type arguments to yourTypedEvents, youdo not need to provide theEventType argument—it will be inferred from your event map.
.on(type, listener[, options])
Adds an event listener for the given event type.
import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<string>}>()emitter.on('hello',(event)=>{// `event` is a `TypedEvent` instance derived from `MessageEvent`.console.log(event.data)})
All methods that add new listeners return anAbortController instance bound to that listener. You can use that controller to cancel the event handling, including mid-air:
All methods that add new listeners also accept an optionaloptions argument. You can use it to configure event handling behavior. For example, you can provide an existingAbortController signal as theoptions.signal value so the attached listener abides by your controller:
Emits the given event and returns a Promise that resolves with the returned data of all matching event listeners, or rejects whenever any of the matching event listeners throws an error.
Emits the given event and returns a generator function that exhausts all matching event listeners. Using a generator gives you granular control over what listeners are called.
import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{hello:TypedEvent<string,number>}>()emitter.on('hello',()=>1)emitter.on('hello',()=>2)for(constlistenerResultofemitter.emitAsGenerator(newTypedEvent('hello',{data:'John'}),)){// Stop event emission if a listener returns a particular value.if(listenerResult===1){break}}
.listeners([type])
Returns the list of all event listeners matching the given event type. If no eventtype is provided, returns the list of all existing event listeners.
.listenerCount([type])
Returns the number of the event listeners matching the given event type. If no eventtype is provided, returns the total number of existing listeners.
.removeListener(type, listener)
Removes the event listener for the given event type.
.removeAllListeners([type])
Removes all event listeners for the given event type. If no eventtype is provided, removes all existing event listeners.
Types
This library also comes with a set of helper types to make your life easier.
Emitter.EventType
Returns theEvent type (or its subtype) representing the given listener.
TheListenerType helper is in itself type-safe, allowing only known event types as the second argument.
Emitter.ListenerReturnType
Returns the return type of the given event's listener.
import{Emitter,TypedEvent}from'rettime'constemitter=newEmitter<{getTotalPrice:TypedEvent<Cart,number>}>()typeCartTotal=Emitter.ListenerReturnType<typeofemitter,'getTotalPrice'>// number
About
A type-safe marriage of `EventTarget` and `EventEmitter`.