Skip to main content

Import

What it does

EventEmitter is a minimal, fully-typed publish/subscribe event bus. It supports standard on/off/emit semantics, one-time listeners, async waiting for events, and introspection. The generic type parameter ensures event names and payloads are type-checked at compile time.

Constructor

The type parameter defines the mapping from event names to their payload types.

Factory

Convenience function that returns a new EventEmitter instance.

Methods

on(event, handler)

Registers a handler for event and returns an unsubscribe function.

once(event, handler)

Like on, but the handler is automatically removed after it fires once. Returns an unsubscribe function in case you need to cancel before it fires.

off(event, handler)

Removes a specific handler for event.

emit(event, ...args)

Fires an event, invoking all registered handlers synchronously in registration order.

removeAllListeners(event?)

Removes all handlers for a specific event, or for all events if no argument is provided.

listenerCount(event)

Returns the number of handlers registered for event.

eventNames()

Returns an array of event names that have at least one registered handler.

getListeners(event)

Returns the array of handler functions registered for event.

waitFor(event, timeout?)

Returns a promise that resolves with the event payload when the event fires, or rejects after timeout ms. Useful for turning event-driven flows into async/await code.

Examples

Typed application bus

One-time initialization hook

Await an event with timeout

Clean up on component unmount

Use waitFor to bridge event-driven APIs with async/await — it’s ideal for waiting on initialization events, one-shot data loads, or test assertions.
emit calls handlers synchronously. If a handler throws, subsequent handlers for the same event will not be called. Wrap handlers in try/catch if fault isolation is needed.