UNPKG

660 BPlain TextView Raw
1export class EventBus {
2 public listeners = {};
3
4 public emit(event: string, data?) {
5 if (this.listeners[event]) {
6 this.listeners[event].forEach(listener => listener(data));
7 }
8 }
9
10 public on(event: string, listener: (data) => void) {
11 if (!this.listeners[event]) {
12 this.listeners[event] = [];
13 }
14 this.listeners[event].push(listener);
15 }
16
17 public unsubscribe(listener: (data) => void) {
18 Object.values(this.listeners).forEach((listeners: any[]) => {
19 const index = listeners.indexOf(listener);
20 if (index > -1) {
21 listeners.splice(index, 1);
22 }
23 });
24 }
25}
26
27export const eventBus = new EventBus();