Created
December 2, 2020 18:29
-
-
Save marutypes/c2c7db21746fb513c8e4e9c2e98e89b8 to your computer and use it in GitHub Desktop.
A simple naive TS event emitter, useful for making nice typed events without remembering how to do it every time
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
type EventMap = Record<string, any>; | |
type EventKey<T extends EventMap> = string & keyof T; | |
type Callback<T> = (params: T) => void; | |
export class EventEmitter<T extends EventMap> { | |
private listeners: { | |
[K in keyof EventMap]?: Array<(p: EventMap[K]) => void>; | |
} = {}; | |
on<K extends EventKey<T>>(key: K, fn: Callback<T[K]>) { | |
this.listeners[key] = (this.listeners[key] || []).concat(fn); | |
} | |
off<K extends EventKey<T>>(key: K, fn: Callback<T[K]>) { | |
this.listeners[key] = (this.listeners[key] || []).filter((f) => f !== fn); | |
} | |
emit<K extends EventKey<T>>(key: K, data: T[K]) { | |
(this.listeners[key] || []).forEach(function (fn: Callback<T[K]>) { | |
fn(data); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment