丰富EventEmitter,添加IndexedEventEmitter

This commit is contained in:
unanmed 2023-08-25 14:23:08 +08:00
parent 41f0394332
commit b2a243b567

View File

@ -1,3 +1,5 @@
import { has } from '../../plugin/utils';
export interface EmitableEvent {
[event: string]: (...params: any) => any;
}
@ -86,4 +88,80 @@ export class EventEmitter<T extends EmitableEvent = {}> {
}
}
}
/**
*
*/
removeAllListeners(): void;
/**
*
* @param event
*/
removeAllListeners(event: keyof T): void;
removeAllListeners(event?: keyof T) {
if (has(event)) this.events[event] = [];
else this.events = {};
}
}
type IndexedSymbol = number | string | symbol;
export class IndexedEventEmitter<
T extends EmitableEvent
> extends EventEmitter<T> {
private fnMap: {
[P in keyof T]?: Map<IndexedSymbol, T[P]>;
} = {};
/**
*
* @param event
* @param symbol
* @param fn
* @param options
*/
onIndex<K extends keyof T>(
event: K,
symbol: IndexedSymbol,
fn: T[K],
options: Partial<ListenerOptions>
) {
const map = this.ensureMap(event);
if (map.has(symbol)) {
console.warn(
`监听${String(event)}出错:已存在标识符为${String(
symbol
)}`
);
this.offIndex(event, symbol);
}
map.set(symbol, fn);
this.on(event, fn, options);
}
/**
*
* @param event
* @param symbol
* @param fn
*/
onceIndex<K extends keyof T>(event: K, symbol: IndexedSymbol, fn: T[K]) {
this.onIndex(event, symbol, fn, { once: true });
}
/**
*
* @param event
* @param symbol
*/
offIndex<K extends keyof T>(event: K, symbol: IndexedSymbol) {
const map = this.ensureMap(event);
const fn = map.get(symbol);
if (!fn) return;
this.off(event, fn);
}
private ensureMap<K extends keyof T>(event: K) {
return this.fnMap[event] ?? new Map<IndexedSymbol, T[K]>();
}
}