Skip to content

Instantly share code, notes, and snippets.

@marutypes
Created December 2, 2020 18:29
Show Gist options
  • Save marutypes/c2c7db21746fb513c8e4e9c2e98e89b8 to your computer and use it in GitHub Desktop.
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
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