Last active
May 31, 2024 19:00
-
-
Save johnloy/9d1be37040f75f4638481adf87576949 to your computer and use it in GitHub Desktop.
Strongly-typed EventTarget custom events with TypeScript
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
// 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