You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

44 lines
1.1 KiB

export type EventMap = {
'dialog:unsafeRoles': {
action: 'confirm' | 'dismiss';
};
// add more events as required
};
export type EventName = keyof EventMap;
export type EventCallback<T extends EventName> = (data: EventMap[T]) => void;
class EventBus {
private listeners: { [K in EventName]?: Array<EventCallback<K>> } = {};
public on<T extends EventName>(event: T, callback: EventCallback<T>): () => void {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event]?.push(callback as any);
return () => {
this.off(event, callback);
};
}
public off<T extends EventName>(event: T, callback: EventCallback<T>): void {
if (!this.listeners[event]) return;
const callbackIndex = this.listeners[event]?.indexOf(callback as any);
if (callbackIndex !== undefined && callbackIndex > -1) {
this.listeners[event]?.splice(callbackIndex, 1);
}
}
public emit<T extends EventName>(event: T, data: EventMap[T]): void {
if (!this.listeners[event]) return;
this.listeners[event]?.forEach(callback => {
callback(data);
});
}
}
export const eventBus = new EventBus();