feat(framework): core EventBus(类型化+故障隔离)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
type Handler = (...args: any[]) => void;
|
||||
|
||||
/** 轻量类型化事件总线。订阅者抛错被隔离,不影响其它订阅者(故障隔离)。 */
|
||||
export class EventBus<Events extends Record<string, any[]> = Record<string, any[]>> {
|
||||
private map = new Map<string, Set<Handler>>();
|
||||
|
||||
on<K extends keyof Events & string>(type: K, fn: (...args: Events[K]) => void): void {
|
||||
let set = this.map.get(type);
|
||||
if (!set) { set = new Set(); this.map.set(type, set); }
|
||||
set.add(fn as Handler);
|
||||
}
|
||||
|
||||
once<K extends keyof Events & string>(type: K, fn: (...args: Events[K]) => void): void {
|
||||
const wrap = (...args: Events[K]) => { this.off(type, wrap as any); (fn as any)(...args); };
|
||||
this.on(type, wrap as any);
|
||||
}
|
||||
|
||||
off<K extends keyof Events & string>(type: K, fn: (...args: Events[K]) => void): void {
|
||||
this.map.get(type)?.delete(fn as Handler);
|
||||
}
|
||||
|
||||
emit<K extends keyof Events & string>(type: K, ...args: Events[K]): void {
|
||||
const set = this.map.get(type);
|
||||
if (!set) return;
|
||||
for (const fn of [...set]) {
|
||||
try { fn(...args); } catch (e) { console.error('[EventBus] handler error:', e); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user