34 lines
865 B
TypeScript
34 lines
865 B
TypeScript
export default class EventBus {
|
|
private static instance: EventBus;
|
|
private listeners: Record<string, Array<(...args: any[]) => void>> = {};
|
|
|
|
private constructor() {}
|
|
|
|
public static getInstance(): EventBus {
|
|
if (!EventBus.instance) {
|
|
EventBus.instance = new EventBus();
|
|
}
|
|
return EventBus.instance;
|
|
}
|
|
|
|
public on(event: string, callback: (...args: any[]) => void): () => void {
|
|
if (!this.listeners[event]) {
|
|
this.listeners[event] = [];
|
|
}
|
|
this.listeners[event].push(callback);
|
|
return () => {
|
|
if (this.listeners[event]) {
|
|
this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
|
|
}
|
|
};
|
|
}
|
|
|
|
public emit(event: string, ...args: any[]): void {
|
|
if (this.listeners[event]) {
|
|
this.listeners[event].forEach(callback => {
|
|
callback(...args);
|
|
});
|
|
}
|
|
}
|
|
}
|