EventBus 事件管理库
EventBus 是一个 TypeScript 事件管理库,用于在模块之间解耦地传递事件。它基于原生 Map 存储订阅者(name -> Map<handler, errorHandler>),提供订阅/退订、一次性订阅、Promise 化、结果收集与错误分发等能力。
核心特性
- 订阅 / 退订:
on/off/offAll/destroy;on/once返回Disposable,便于统一管理生命周期。 - 一次性订阅:
once,事件触发一次后自动退订。 - Promise 化:
promise,返回一个会在事件触发时 resolve 的 Promise,出错时 reject。 - 收集结果:
gather/gatherMap,获取所有 handler 的返回结果。 - 错误处理:
error方法 +ErrorHandler,将错误分发给对应事件的错误处理器。 - 别名:
subscribe/unsubscribe/publish,分别等价于on/off/emit。 - 零依赖:底层只依赖内建的
Map,无第三方运行时依赖。 - 全局单例:具名导出
eventBus,可在多处共享同一总线。
环境要求
- Node.js 运行时(支持 ESM 与原生
Map)。 - TypeScript 或支持静态类型的 JS 环境(内置
.d.ts类型声明)。 - 包以 ESM 模块发布(
package.json中"type": "module")。
安装
bash
npm install @ai-zen/event-bus
# 或
pnpm add @ai-zen/event-bus快速示例
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!