Created
September 27, 2022 13:10
-
-
Save fjahn/853f277eda907453e3f46055b299c3bb to your computer and use it in GitHub Desktop.
Typesafe Event Emitter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class OpenEventEmitter<T> implements EventEmitter<T> { | |
private readonly handlers: { [eventName in keyof T]?: ((value: T[eventName]) => void)[] } | |
constructor() { | |
this.handlers = {} | |
} | |
getClosedEmitter(): EventEmitter<T> { | |
return this | |
} | |
emit<K extends keyof T>(event: K, value: T[K]): void { | |
this.handlers[event]?.forEach(h => h(value)) | |
} | |
on<K extends keyof T>(event: K, handler: (value: T[K]) => void): void { | |
if(!this.handlers[event]) | |
this.handlers[event] = [] | |
this.handlers[event]?.push(handler) | |
} | |
} | |
export default interface EventEmitter<T> { | |
on<K extends keyof T>(event: K, handler: (value: T[K]) => void): void | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment