43 lines
981 B
TypeScript
Raw Normal View History

2022-12-01 22:26:41 +08:00
import Singleton from '../Base/Singleton'
import { EventEnum } from '../Enum';
interface IItem {
2022-12-07 22:24:46 +08:00
cb: Function;
2022-12-01 22:26:41 +08:00
ctx: unknown;
}
export default class EventManager extends Singleton {
static get Instance() {
return super.GetInstance<EventManager>();
}
private map: Map<EventEnum, Array<IItem>> = new Map();
2022-12-07 22:24:46 +08:00
on(event: EventEnum, cb: Function, ctx: unknown) {
2022-12-01 22:26:41 +08:00
if (this.map.has(event)) {
2022-12-07 22:24:46 +08:00
this.map.get(event).push({ cb, ctx });
2022-12-01 22:26:41 +08:00
} else {
2022-12-07 22:24:46 +08:00
this.map.set(event, [{ cb, ctx }]);
2022-12-01 22:26:41 +08:00
}
}
2022-12-07 22:24:46 +08:00
off(event: EventEnum, cb: Function, ctx: unknown) {
2022-12-01 22:26:41 +08:00
if (this.map.has(event)) {
2022-12-07 22:24:46 +08:00
const index = this.map.get(event).findIndex(i => cb === i.cb && i.ctx === ctx);
2022-12-01 22:26:41 +08:00
index > -1 && this.map.get(event).splice(index, 1);
}
}
emit(event: EventEnum, ...params: unknown[]) {
if (this.map.has(event)) {
2022-12-07 22:24:46 +08:00
this.map.get(event).forEach(({ cb, ctx }) => {
cb.apply(ctx, params)
2022-12-01 22:26:41 +08:00
});
}
}
clear() {
this.map.clear();
}
}