1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/packages/utility-features/event-emitter/src/event-emitter.ts
Sebastian Malton fa44b795d4 chore: Improve linting within @k8slens/core
- Turning on @typescript-eslint/recommended-requiring-type-checking
- Turning off @typescript-eslint/no-unnecessary-type-assertion (due too many false positives)
- Making @typescript-eslint/no-explicit-any an error (except in tests)

Signed-off-by: Sebastian Malton <sebastian@malton.name>
2023-06-01 09:17:17 -04:00

37 lines
956 B
TypeScript

export interface EventEmitterOptions {
once?: boolean; // call once and remove
prepend?: boolean; // put listener to the beginning
}
export type EventEmitterCallback<D extends unknown[]> = (...data: D) => void | boolean;
export class EventEmitter<D extends unknown[]> {
protected listeners: [EventEmitterCallback<D>, EventEmitterOptions][] = [];
addListener(callback: EventEmitterCallback<D>, options: EventEmitterOptions = {}) {
const fn = options.prepend ? "unshift" : "push";
this.listeners[fn]([callback, options]);
}
removeListener(callback: EventEmitterCallback<D>) {
this.listeners = this.listeners.filter(([cb]) => cb !== callback);
}
removeAllListeners() {
this.listeners.length = 0;
}
emit(...data: D) {
for (const [callback, { once }] of this.listeners) {
if (once) {
this.removeListener(callback);
}
if (callback(...data) === false) {
break;
}
}
}
}