BattleEventManager.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { BattleBase } from "./BattleBase";
  2. /***
  3. * 事件管理器
  4. * 事件可一对一也可一对多
  5. */
  6. export class BattleEventManager {
  7. private static _instance: BattleEventManager = null;
  8. //事件
  9. private _events = new Map<string, { id: number, func: Function, target: any }[]>();
  10. //事件ID缓存
  11. private _targets = new Set<number>();
  12. static get instance() {
  13. if (!this._instance) {
  14. this._instance = new BattleEventManager();
  15. this._instance.constructor = null;
  16. }
  17. return this._instance;
  18. }
  19. constructor() {
  20. this._events.clear();
  21. this._targets.clear();
  22. }
  23. /**
  24. * 添加事件
  25. * @param name 事件名
  26. * @param callback 回调函数
  27. * @param target 回调目标
  28. * @param uuid 事件唯一ID,如果在组件调用不需要该值
  29. */
  30. addEvent(name: string, callback: (...val: any[]) => void, target: BattleBase|number) {
  31. if (!name || !callback || !target ) {
  32. console.error(`添加事件失败name,callback或者target为空.`);
  33. return false;
  34. }
  35. if (!this._events.has(name)) {
  36. this._events.set(name, []);
  37. }
  38. let uuid = target instanceof BattleBase ? target.uuid : target;
  39. this._events.get(name).push({ id: uuid, func: callback, target: target });
  40. if (!this._targets.has(uuid)) {
  41. this._targets.add(uuid);
  42. }
  43. return true;
  44. }
  45. /**
  46. * 发射事件
  47. * @param name 事件名
  48. * @param val 传递的数据
  49. */
  50. fireEvent(name: string, ...val: any[]) {
  51. let event = this._events.get(name);
  52. if (event) {
  53. for (let i = event.length - 1; i >= 0; --i) {
  54. if (event[i].target instanceof BattleBase) {
  55. if (event[i].target.uuid === event[i].id) {
  56. event[i].func(...val);
  57. } else {
  58. event.splice(i, 1);
  59. }
  60. } else {
  61. event[i].func(...val);
  62. }
  63. }
  64. }
  65. }
  66. /**
  67. * 移除组件所有事件
  68. * @param target 目标组件或事件的唯一标识
  69. */
  70. removeEvent(target: BattleBase | number) {
  71. let uuid = (typeof target === "number") ? target : target?.uuid;
  72. if (this._targets.has(uuid)) {
  73. this._targets.delete(uuid);
  74. this._events.forEach((events, name) => {
  75. for (let i = events.length - 1; i >= 0; --i) {
  76. if (events[i].id === uuid) {
  77. events.splice(i, 1);
  78. }
  79. }
  80. if (events.length === 0) {
  81. this._events.delete(name);
  82. }
  83. });
  84. }
  85. }
  86. removeAll() {
  87. this._events.clear();
  88. this._targets.clear();
  89. }
  90. }