eventEmitter.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { _decorator, Component, Node } from "cc";
  2. const { ccclass, property } = _decorator;
  3. interface IEventData {
  4. func: Function;
  5. target: any;
  6. }
  7. interface IEvent {
  8. [eventName: string]: IEventData[];
  9. }
  10. @ccclass("eventEmitter")
  11. export class eventEmitter extends Component {
  12. public static handle: IEvent = {};
  13. public static on(eventName: string, cb:Function, target?: any){
  14. if(!this.handle[eventName]){
  15. this.handle[eventName] = [];
  16. }
  17. const data: IEventData = { func: cb, target };
  18. this.handle[eventName].push(data);
  19. }
  20. public static off(eventName: string, cb: Function, target?: any){
  21. const list = this.handle[eventName];
  22. if(!list || list.length <=0){
  23. return;
  24. }
  25. for (let i = 0; i < list.length; i++) {
  26. const event = list[i];
  27. if(event.func === cb && (!target || target === event.target)){
  28. list.splice(i, 1);
  29. break;
  30. }
  31. }
  32. }
  33. public static emit (eventName: string, ...args:any){
  34. const list = this.handle[eventName];
  35. if (!list || list.length <= 0) {
  36. return;
  37. }
  38. for (let i = 0; i < list.length; i++) {
  39. const event = list[i];
  40. event.func.apply(event.target, args);
  41. }
  42. }
  43. }