Last active
May 21, 2023 10:44
-
-
Save tomaswrobel/2012786a9d0f13426195c91e26ef90d8 to your computer and use it in GitHub Desktop.
Emitting events natively.
This file contains hidden or 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 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