Skip to content

Getting Started

This chapter introduces how to install and use @ai-zen/event-bus.

Installation

bash
npm install @ai-zen/event-bus
# or
pnpm add @ai-zen/event-bus

Import

ts
import EventBus, { eventBus } from "@ai-zen/event-bus";
  • EventBus: the default export, an instantiable class.
  • eventBus: the named export, a global singleton shareable across multiple places.

Create an Instance

ts
const bus = new EventBus();

If you don't want to maintain multiple instances, you can use the global singleton directly:

ts
import { eventBus } from "@ai-zen/event-bus";
eventBus.on("event", handler);

Subscribe and Emit

ts
const bus = new EventBus();

bus.on("greet", (name: string) => {
  console.log(`Hello, ${name}!`);
});

bus.emit("greet", "AI-Zen"); // Hello, AI-Zen!

emit passes the subsequent arguments to all subscribed handlers as-is.

Unsubscribe

Using off

ts
const handler = () => console.log("hi");
bus.on("greet", handler);

bus.off("greet", handler); // Unsubscribe this handler

Using Disposable

on / once return a Disposable which can be used to unsubscribe via dispose():

ts
const disposable = bus.on("greet", handler);
disposable.dispose(); // equivalent to bus.off("greet", handler)

Clearing an event or everything

ts
bus.offAll("greet"); // Remove all handlers of "greet"
bus.destroy();       // Clear all subscriptions

One-time subscription: once

After subscribing with once, the handler automatically unsubscribes the first time the event fires:

ts
bus.once("greet", (name) => {
  console.log(`Hello once, ${name}!`);
});

bus.emit("greet", "A"); // Hello once, A!
bus.emit("greet", "B"); // No longer fires

Promise-ification: promise

promise returns a Promise that resolves when the event fires:

ts
const result = await bus.promise("reply");
bus.emit("reply", "done");
// result === "done"

Aggregating results: gather / gatherMap

gather returns an array of all handlers' return results; gatherMap returns a Map keyed by handler:

ts
bus.on("calc", () => 1);
bus.on("calc", () => 2);

const results = bus.gather<number>("calc");       // [1, 2]
const resultsMap = bus.gatherMap<number>("calc"); // Map(handler -> result)

Error handling: error

Register an error handler for an event, then dispatch errors via error:

ts
bus.on("load", () => {
  // handle normally
}, (reason) => {
  console.error("load failed:", reason);
});

bus.error("load", new Error("boom")); // triggers the event's error handler

It can also be combined with promise:

ts
bus.promise("load").catch((reason) => {
  console.error("load failed:", reason);
});
bus.error("load", new Error("boom"));

References

MIT / ISC License