UNPKG

@known-as-bmf/hookable

Version:
46 lines (35 loc) 1.13 kB
type Action<Args extends readonly any[]> = (...args: Args) => void; interface EventTypes { [name: string]: readonly any[]; } interface EventCache { [name: string]: Set<Action<any[]>>; } export class EventEmitter<T extends EventTypes> { private _cache: EventCache = {}; public emit<E extends keyof T>(name: E, args: T[E]): void { if (!this._cache[name as string]) { return; } this._cache[name as string].forEach((callback) => { callback(...args); }); } public on<E extends keyof T>(name: E, callback: Action<T[E]>): void { if (!this._cache[name as string]) { this._cache[name as string] = new Set<Action<any[]>>(); } this._cache[name as string].add(callback); } public off<E extends keyof T>(name: E, callback: Action<T[E]>): void { if (!this._cache[name as string]) { return; } this._cache[name as string].add(callback); } } const t = new EventEmitter<{ test: [someValue: string] }>(); t.emit('test', ['a']); const handler = (): void => {}; t.on('test', handler); t.off('test', handler);