Created
July 25, 2019 09:11
-
-
Save Schniz/0571c80a462787e69438b1cb0ed2cda4 to your computer and use it in GitHub Desktop.
Typesafe event emitters
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
class EventEmitter<T extends object> { | |
private readonly listeners: { | |
[key in keyof T]?: ((value: T[key]) => void)[]; | |
} = {}; | |
emit<Event extends keyof T>(event: Event, value: T[Event]) { | |
const listeners = this.listeners[event]; | |
if (listeners) { | |
listeners.forEach(listener => listener(value)); | |
} | |
} | |
listen<Event extends keyof T>(event: Event, onChange: (e: T[Event]) => void) { | |
let listeners = this.listeners[event] || []; | |
if (!listeners) { | |
listeners = []; | |
this.listeners[event] = listeners; | |
} | |
const index = listeners.push(onChange) - 1; | |
return () => { | |
if (listeners) { | |
listeners.splice(index, 1); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment