21700: Install Bundler system-wide in Rails postinst
[arvados.git] / services / workbench2 / src / lib / cwl-svg / utils / event-hub.ts
1 export class EventHub {
2     public readonly handlers: { [event: string]: Function[] };
3
4     constructor(validEventList: string[]) {
5         this.handlers = validEventList.reduce((acc, ev) => Object.assign(acc, {[ev]: []}), {});
6     }
7
8     on(event: string, handler: Function) {
9         this.guard(event, "subscribe to");
10         this.handlers[event].push(handler);
11
12         return () => this.off(event, handler);
13     }
14
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);
18     }
19
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);
24         }
25     }
26
27     empty() {
28         for (let event in this.handlers) {
29             this.handlers[event] = [];
30         }
31     }
32
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(", ")}”`);
37         }
38     }
39 }