2019-05-16 08:05:36 +02:00
|
|
|
/**
|
|
|
|
* Generic Event Emitter class following a subscribe/publish paradigm.
|
|
|
|
*/
|
|
|
|
import { IMap } from "../types";
|
|
|
|
|
|
|
|
type cbFn = (...args: any[]) => any;
|
|
|
|
|
|
|
|
export interface ISubscriber {
|
|
|
|
/**
|
|
|
|
* Callback function that will be run when an event is emitted
|
|
|
|
*/
|
|
|
|
cb: cbFn;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Name/identifier for this subscriber
|
|
|
|
*/
|
|
|
|
id: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class EventEmitter {
|
|
|
|
/**
|
|
|
|
* Map of Subscriber name -> Callback function
|
|
|
|
*/
|
|
|
|
subscribers: IMap<cbFn> = {};
|
|
|
|
|
|
|
|
constructor(subs?: ISubscriber[]) {
|
|
|
|
if (Array.isArray(subs)) {
|
|
|
|
for (const s of subs) {
|
|
|
|
this.addSubscriber(s);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-01 09:17:31 +02:00
|
|
|
addSubscriber(s: ISubscriber): void {
|
2019-05-16 08:05:36 +02:00
|
|
|
this.subscribers[s.id] = s.cb;
|
|
|
|
}
|
|
|
|
|
|
|
|
emitEvent(...args: any[]): void {
|
|
|
|
for (const s in this.subscribers) {
|
2021-05-01 09:17:31 +02:00
|
|
|
const sub = this.subscribers[s];
|
2019-05-16 08:05:36 +02:00
|
|
|
|
2021-05-01 09:17:31 +02:00
|
|
|
sub(args);
|
2019-05-16 08:05:36 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-01 09:17:31 +02:00
|
|
|
removeSubscriber(id: string): void {
|
2019-05-16 08:05:36 +02:00
|
|
|
delete this.subscribers[id];
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|