export type Listener = (event: T) => any; export class Emitter { private listeners: {[key: string]: Listener} = {}; constructor() { } emit(e: T) { Object.values(this.listeners).forEach(l => l(e)); } listen(fn: Listener): () => {}; listen(key: string, fn: Listener): () => {}; listen(keyOrFn: string | Listener, fn?: Listener): () => {} { const func: any = fn ? fn : keyOrFn; const key: string = typeof keyOrFn == 'string' ? keyOrFn : `_${Object.keys(this.listeners).length.toString()}`; this.listeners[key] = func; return () => delete this.listeners[key]; } once(fn: Listener) { const stop = this.listen(e => { fn(e); stop(); }); } }