2022-12-01 22:26:41 +08:00

43 lines
1.0 KiB
TypeScript

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<EventManager>();
}
private map: Map<EventEnum, Array<IItem>> = 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();
}
}