1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/dashboard/client/utils/eventEmitter.ts
Sebastian Malton b1ff34879a cleanup Lens repo with tighter linting
Signed-off-by: Sebastian Malton <smalton@mirantis.com>
2020-07-09 17:00:23 -04:00

44 lines
1.0 KiB
TypeScript

// Custom event emitter
interface Options {
once?: boolean; // call once and remove
prepend?: boolean; // put listener to the beginning
}
type Callback<D extends [...any[]]> = (...data: D) => void | boolean;
export class EventEmitter<D extends [...any[]]> {
protected listeners = new Map<Callback<D>, Options>();
addListener(callback: Callback<D>, options: Options = {}): void {
if (options.prepend) {
const listeners = [...this.listeners];
listeners.unshift([callback, options]);
this.listeners = new Map(listeners);
} else {
this.listeners.set(callback, options);
}
}
removeListener(callback: Callback<D>): void {
this.listeners.delete(callback);
}
removeAllListeners(): void {
this.listeners.clear();
}
emit(...data: D): void {
[...this.listeners].every(([callback, options]) => {
if (options.once) {
this.removeListener(callback);
}
const result = callback(...data);
if (result === false) {
return;
} // break cycle
return true;
});
}
}