EventBus Event Management Library
EventBus is a TypeScript event management library used to decouple event delivery between modules. It is backed by the native Map to store subscribers (name -> Map<handler, errorHandler>), providing subscribe/unsubscribe, one-time subscription, Promise-ification, result aggregation and error dispatch capabilities.
Core Features
- Subscribe / Unsubscribe:
on/off/offAll/destroy;on/oncereturn aDisposable, making lifecycle management easy. - One-time subscription:
onceautomatically unsubscribes after the event fires once. - Promise-ification:
promisereturns a Promise that resolves when the event fires and rejects on error. - Aggregate results:
gather/gatherMapretrieve the return results of all handlers. - Error handling: the
errormethod plusErrorHandlerdispatch errors to the corresponding event's error handler. - Aliases:
subscribe/unsubscribe/publishare equivalent toon/off/emitrespectively. - Zero dependency: relies only on the built-in
Map; no third-party runtime dependencies. - Global singleton: the named export
eventBuscan share the same bus across multiple places.
Requirements
- Node.js runtime (supports ESM and the native
Map). - TypeScript or a JS environment with static type support (built-in
.d.tstype declarations). - The package is published as an ESM module (
"type": "module"inpackage.json).
Installation
bash
npm install @ai-zen/event-bus
# or
pnpm add @ai-zen/event-busQuick Example
ts
import EventBus, { eventBus } from "@ai-zen/event-bus";
const bus = new EventBus();
bus.on("greet", (name: string) => {
console.log(`Hello, ${name}!`);
});
bus.emit("greet", "AI-Zen"); // Hello, AI-Zen!For more complete usage, see Getting Started and API Reference.
References
- Getting Started — installation, creating instances, subscribe/unsubscribe, and once/promise/gather and error handling examples.
- API Reference — full documentation of
on,off,emit,once,promise,gather,gatherMap,error, etc.