Skip to content

Instantly share code, notes, and snippets.

@tomaswrobel
Last active May 21, 2023 10:44
Show Gist options
  • Save tomaswrobel/2012786a9d0f13426195c91e26ef90d8 to your computer and use it in GitHub Desktop.
Save tomaswrobel/2012786a9d0f13426195c91e26ef90d8 to your computer and use it in GitHub Desktop.
Emitting events natively.
class Emitter<E extends Record<string, new (...args: any[]) => Event>> extends EventTarget {
constructor(public events: E) {
super();
}
on<T extends keyof E>(event: T, listener: (e: InstanceType<E[T]>) => void) {
this.addEventListener(event as string, listener as (e: Event) => void);
return this;
}
once<T extends keyof E>(event: T, listener: (e: InstanceType<E[T]>) => void) {
this.addEventListener(event as string, listener as (e: Event) => void, { once: true });
return this;
}
off<T extends keyof E>(event: T, listener: (e: InstanceType<E[T]>) => void) {
this.removeEventListener(event as string, listener as (e: Event) => void);
return this;
}
emit<T extends keyof E>(event: T, ...args: ConstructorParameters<E[T]>) {
this.dispatchEvent(new this.events[event](...args));
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment