Skip to content

Instantly share code, notes, and snippets.

@johnloy
Last active May 31, 2024 19:00
Show Gist options
  • Save johnloy/9d1be37040f75f4638481adf87576949 to your computer and use it in GitHub Desktop.
Save johnloy/9d1be37040f75f4638481adf87576949 to your computer and use it in GitHub Desktop.
Strongly-typed EventTarget custom events with TypeScript
// Credits: https://medium.com/@saeed.asghari.241/create-custom-event-in-typescript-8219054cee5d
class EventBus extends EventTarget {
constructor() {
super()
}
addCustomEventListener<T extends Partial<Record<string, any>>>(
type: string,
listener: (event: CustomEvent<T>) => void,
options?: boolean | AddEventListenerOptions
) {
const eventListener: EventListener = (event: Event) => {
listener(event as CustomEvent<T>)
}
this.addEventListener(type, eventListener, options)
}
dispatchCustomEvent<T>(type: string, detail: T) {
const customEvent = new CustomEvent(type, { detail })
this.dispatchEvent(customEvent)
}
}
/**
* @example
* const myCustomEvent = EventManager.getInstance('eventOne')
* myCustomEvent.addCustomEventListener('myMessage', (event) => {
* if (event.detail && event.detail.message) {
* console.log(event.detail.message);
* }
* });
*/
export class EventManager {
private static instances: Map<string, EventBus> = new Map()
public static getInstance(name: string): EventBus {
if (!EventManager.instances.has(name)) {
EventManager.instances.set(name, new EventBus())
}
return EventManager.instances.get(name)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment