@yingyeothon/event-broker
v2.6.0
Published
Type-safe async event broker with add/remove/once listener semantics.
Readme
@yingyeothon/event-broker
A tiny, type-safe event broker: define your events as a TypeScript event map, create a broker with createEventBroker, and fire events into synchronous or asynchronous handlers. Handlers run in registration order and each async handler is awaited before the next one runs.
Firing an event is a sequencing point: handlers run in registration order and each is awaited before the next.
sequenceDiagram
participant P as your code
participant B as the broker
participant H1 as handler 1
participant H2 as handler 2
P->>B: fire
B->>H1: await
H1-->>B: done
B->>H2: await
H2-->>B: done
B-->>P: resolves only nowInstall
npm install @yingyeothon/event-brokerUsage
ESM:
import { createEventBroker } from "@yingyeothon/event-broker";
interface ReaderEventMap {
read: string;
error: Error;
}
const reader = createEventBroker<ReaderEventMap>();
reader.on("read", console.log).once("error", console.error);
try {
for (const line of ["hello", "world"]) {
await reader.fire("read", line);
}
} catch (error) {
await reader.fire("error", error as Error);
}CJS:
const { createEventBroker } = require("@yingyeothon/event-broker");
const ticker = createEventBroker();
const onTick = (value) => console.log("tick", value);
ticker.on("tick", onTick);
ticker.fire("tick", 1).then(() => ticker.off("tick", onTick));There is no need to await the result of fire when every handler is synchronous.
Public API
createEventBroker<E>()— factory that returns anEventBroker<E>.EventBroker<E>— interface. Listener registration viaon(name, handler),once(name, handler), andoff(name, handler), each returning the broker for chaining. Events are dispatched withfire(name, event), which awaits handlers one by one in registration order and resolves totruewhen at least one handler was registered. A handler that throws (or rejects) makesfirereject and skips the remaining handlers.EventListenable<E>— interface with the listener-facing surface:on,once, andoff.EventHandler<T>— type of an event handler:(event: T) => unknown, where a returned promise is awaited.
Migrating from the legacy package
EventBroker<E>is now an interface, not a class: replacenew EventBroker()(or subclassing) withcreateEventBroker<E>().fireis part of the public surface instead of a protected method, so dispatching no longer requires a subclass.onceandoffare new; the legacy broker only supportedon.EventListenable<E>now declaresonceandoffin addition toon, so custom implementations must provide all three.- Handlers are snapshotted per
firecall: handlers added or removed during dispatch take effect from the nextfire, whereas the legacy broker iterated the live handler array. fireresolves tofalsewhen the event has no remaining handlers (the legacy broker returnedfalseonly when the event name had never been registered).
