From 9271e25dd9cad828ed95d774127aea02fb7775e0 Mon Sep 17 00:00:00 2001 From: unanmed <1319491857@qq.com> Date: Tue, 14 Nov 2023 22:20:30 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=87=AA=E5=AE=9A=E4=B9=89emitter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/common/eventEmitter.ts | 42 +++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 7 deletions(-) diff --git a/src/core/common/eventEmitter.ts b/src/core/common/eventEmitter.ts index caa9e90..9a801c0 100644 --- a/src/core/common/eventEmitter.ts +++ b/src/core/common/eventEmitter.ts @@ -15,12 +15,21 @@ interface ListenerOptions { immediate: boolean; } +type EmitFn any> = ( + events: Listener[], + ...params: Parameters +) => any; + export class EventEmitter { private events: { [P in keyof T]?: Listener[]; } = {}; private emitted: (keyof T)[] = []; + private emitter: { + [P in keyof T]?: EmitFn; + } = {}; + /** * 监听某个事件 * @param event 要监听的事件类型 @@ -74,21 +83,40 @@ export class EventEmitter { * @param event 要触发的事件类型 * @param params 传入的参数 */ - emit(event: K, ...params: Parameters) { + emit( + event: K, + ...params: Parameters + ): ReturnType[]; + emit(event: K, ...params: Parameters): R; + emit(event: K, ...params: Parameters): any { if (!this.emitted.includes(event)) { this.emitted.push(event); } const events = (this.events[event] ??= []); - for (let i = 0; i < events.length; i++) { - const e = events[i]; - e.fn(...(params as any)); - if (e.once) { - events.splice(i, 1); - i--; + if (!!this.emitter[event]) { + const returns = this.emitter[event]!(events, ...params); + this.events[event] = events.filter(v => !v.once); + return returns; + } else { + const returns: ReturnType[] = []; + for (let i = 0; i < events.length; i++) { + const e = events[i]; + returns.push(e.fn(...(params as any))); } + this.events[event] = events.filter(v => !v.once); + return returns; } } + /** + * 设置一个事件的执行器(emitter) + * @param event 要设置的事件 + * @param fn 事件执行器,留空以清除触发器 + */ + setEmitter(event: K, fn?: EmitFn) { + this.emitter[event] = fn; + } + /** * 取消监听所有的事件,删除所有监听函数 */