123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import { BattleBase } from "./BattleBase";
- export class BattleEventManager {
- private static _instance: BattleEventManager = null;
-
- private _events = new Map<string, { id: number, func: Function, target: any }[]>();
-
- private _targets = new Set<number>();
- static get instance() {
- if (!this._instance) {
- this._instance = new BattleEventManager();
- this._instance.constructor = null;
- }
- return this._instance;
- }
-
- constructor() {
- this._events.clear();
- this._targets.clear();
- }
-
- addEvent(name: string, callback: (...val: any[]) => void, target: BattleBase|number) {
- if (!name || !callback || !target ) {
- console.error(`添加事件失败name,callback或者target为空.`);
- return false;
- }
- if (!this._events.has(name)) {
- this._events.set(name, []);
- }
- let uuid = target instanceof BattleBase ? target.uuid : target;
-
- this._events.get(name).push({ id: uuid, func: callback, target: target });
- if (!this._targets.has(uuid)) {
- this._targets.add(uuid);
- }
- return true;
- }
-
- fireEvent(name: string, ...val: any[]) {
- let event = this._events.get(name);
- if (event) {
- for (let i = event.length - 1; i >= 0; --i) {
- if (event[i].target instanceof BattleBase) {
- if (event[i].target.uuid === event[i].id) {
- event[i].func(...val);
- } else {
- event.splice(i, 1);
- }
- } else {
- event[i].func(...val);
- }
- }
- }
- }
-
- removeEvent(target: BattleBase | number) {
- let uuid = (typeof target === "number") ? target : target?.uuid;
- if (this._targets.has(uuid)) {
- this._targets.delete(uuid);
- this._events.forEach((events, name) => {
- for (let i = events.length - 1; i >= 0; --i) {
- if (events[i].id === uuid) {
- events.splice(i, 1);
- }
- }
- if (events.length === 0) {
- this._events.delete(name);
- }
- });
- }
- }
- removeAll() {
- this._events.clear();
- this._targets.clear();
- }
- }
|