EventMgr.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import DateTime from "../help/DateTime";
  2. import { GameEvent } from "./GameEvent";
  3. const { ccclass, property } = cc._decorator;
  4. @ccclass
  5. export default class EventMgr extends cc.Component {
  6. public static Instance: EventMgr = null;
  7. private events_map = {};
  8. onLoad() {
  9. if (EventMgr.Instance === null) {
  10. EventMgr.Instance = this;
  11. }
  12. else {
  13. this.destroy();
  14. return;
  15. }
  16. }
  17. // func(event_name: string, udata: any)
  18. public add_event_listenner(event_name, caller, func) {
  19. if (!this.events_map[event_name]) {
  20. this.events_map[event_name] = [];
  21. }
  22. var event_queue = this.events_map[event_name];
  23. event_queue.push({
  24. caller: caller,
  25. func: func
  26. });
  27. }
  28. public remove_event_listenner(event_name, caller, func) {
  29. if (!this.events_map[event_name]) {
  30. return;
  31. }
  32. var event_queue = this.events_map[event_name];
  33. for(var i = 0; i < event_queue.length; i ++) {
  34. var obj = event_queue[i];
  35. if (obj.caller == caller && obj.func == func) {
  36. // if (event_name==GameEvent.HeroSuperSkill) {
  37. // console.error("移除监听列表:"+DateTime.formatDate());
  38. // console.error(obj.caller);
  39. // }
  40. event_queue.splice(i, 1);
  41. break;
  42. }
  43. }
  44. if (event_queue.length <= 0) {
  45. this.events_map[event_name] = null;
  46. }
  47. }
  48. public remove_event_all(event_name, caller) {
  49. if (!this.events_map[event_name]) {
  50. return;
  51. }
  52. var event_queue = this.events_map[event_name];
  53. for(var i = 0; i < event_queue.length; i ++) {
  54. var obj = event_queue[i];
  55. if (obj.caller == caller) {
  56. event_queue.splice(i, 1);
  57. break;
  58. }
  59. }
  60. if (event_queue.length <= 0) {
  61. this.events_map[event_name] = null;
  62. }
  63. }
  64. public dispatch_event(event_name, udata = null) {
  65. if (!this.events_map[event_name]) {
  66. return;
  67. }
  68. var event_queue = this.events_map[event_name];
  69. // if (event_name==GameEvent.HeroSuperSkill) {
  70. // console.warn("事件监听列表:"+ event_queue.length+" "+DateTime.formatDate());
  71. // }
  72. let eQueue= event_queue.slice();//克隆数组event_queue,否则在遍历数组过程中移除数据,会导致遍历出错
  73. for(var i = 0; i < eQueue.length; i ++) {
  74. var obj = eQueue[i];
  75. // if (event_name==GameEvent.HeroSuperSkill) {
  76. // console.warn(DateTime.formatDate());
  77. // console.warn(obj.caller);
  78. // }
  79. obj.func.call(obj.caller, event_name, udata);
  80. }
  81. }
  82. }