44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
export class EventBroadcaster {
|
|
private listeners: Map<string, Set<Function>> = new Map()
|
|
|
|
/**
|
|
* Assigns a listener for the specified event
|
|
* @param event event name
|
|
* @param listener function to call when the event is emitted
|
|
*/
|
|
on(event: string, listener: Function) {
|
|
if (!this.listeners.has(event))
|
|
this.listeners.set(event, new Set())
|
|
this.listeners.get(event)!.add(listener)
|
|
}
|
|
|
|
/**
|
|
* Removes a listener from the specified event
|
|
* @param event event name
|
|
* @param listener function to remove
|
|
*/
|
|
off(event: string, listener: Function) {
|
|
if (this.listeners.has(event))
|
|
this.listeners.get(event)!.delete(listener)
|
|
}
|
|
|
|
/**
|
|
* Removes all listeners for the specified event
|
|
* @param event event name
|
|
*/
|
|
clear(event: string) {
|
|
if (this.listeners.has(event))
|
|
this.listeners.get(event)!.clear()
|
|
}
|
|
|
|
/**
|
|
* Emits an event with the given arguments
|
|
* @param event event name
|
|
* @param args arguments to pass to the listeners
|
|
*/
|
|
emit(event: string, ...args: any[]) {
|
|
if (this.listeners.has(event))
|
|
this.listeners.get(event)!.forEach((listener) => listener(...args))
|
|
}
|
|
}
|