import Singleton from '../Base/Singleton' import { EventEnum } from '../Enum'; interface IItem { func: Function; ctx: unknown; } export default class EventManager extends Singleton { static get Instance() { return super.GetInstance(); } private map: Map> = new Map(); on(event: EventEnum, func: Function, ctx?: unknown) { if (this.map.has(event)) { this.map.get(event).push({ func, ctx }); } else { this.map.set(event, [{ func, ctx }]); } } off(event: EventEnum, func: Function, ctx?: unknown) { if (this.map.has(event)) { const index = this.map.get(event).findIndex(i => func === i.func && i.ctx === ctx); index > -1 && this.map.get(event).splice(index, 1); } } emit(event: EventEnum, ...params: unknown[]) { if (this.map.has(event)) { this.map.get(event).forEach(({ func, ctx }) => { ctx ? func.apply(ctx, params) : func(...params); }); } } clear() { this.map.clear(); } }