1 export class EventHub {
2 public readonly handlers: { [event: string]: Function[] };
4 constructor(validEventList: string[]) {
5 this.handlers = validEventList.reduce((acc, ev) => Object.assign(acc, {[ev]: []}), {});
8 on(event: string, handler: Function) {
9 this.guard(event, "subscribe to");
10 this.handlers[event].push(handler);
12 return () => this.off(event, handler);
15 off(event: string, handler: Function) {
16 this.guard(event, "unsubscribe from");
17 return this.handlers[event].splice(this.handlers[event].findIndex(h => handler === h), 1);
20 emit(event: string, ...data: any[]) {
21 this.guard(event, "emit");
22 for (let i = 0; i < this.handlers[event].length; i++) {
23 this.handlers[event][i](...data);
28 for (let event in this.handlers) {
29 this.handlers[event] = [];
33 private guard(event: string, verb: string) {
34 if (!this.handlers[event]) {
35 console.warn(`Trying to ${verb} a non-supported event “${event}”.
36 Supported events are: ${Object.keys(this.handlers).join(", ")}”`);