123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import { BattleBase } from "./BattleBase";
- /***
- * 事件管理器
- * 事件可一对一也可一对多
- */
- export class BattleEventManager {
- private static _instance: BattleEventManager = null;
- //事件
- private _events = new Map<string, { id: number, func: Function, target: any }[]>();
- //事件ID缓存
- 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();
- }
- /**
- * 添加事件
- * @param name 事件名
- * @param callback 回调函数
- * @param target 回调目标
- * @param uuid 事件唯一ID,如果在组件调用不需要该值
- */
- 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;
- }
- /**
- * 发射事件
- * @param name 事件名
- * @param val 传递的数据
- */
- 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);
- }
- }
- }
- }
- /**
- * 移除组件所有事件
- * @param target 目标组件或事件的唯一标识
- */
- 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();
- }
- }
|