EventDispatcher.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @en the classes inherit from class:EventDispatcher will have the ability to dispatch events.
  3. * @zh 事件派发器,继承自EventDispatcher的类将拥有事件派发能力
  4. *
  5. * */
  6. export class EventDispatcher {
  7. private _handlersMap:any = {};
  8. public on(event: string|number, cb: Function, thisArg?: any, args?: [], once?: boolean) {
  9. if((!event && event!=0) || !cb){
  10. return;
  11. }
  12. let handlers = this._handlersMap[event];
  13. if (!handlers) {
  14. handlers = this._handlersMap[event] = [];
  15. }
  16. handlers.push({
  17. event: event,
  18. cb: cb,
  19. thisArg: thisArg,
  20. once: once,
  21. args: args
  22. });
  23. }
  24. public once(event: string|number, cb: Function, thisArg: any, args: []) {
  25. this.on(event, cb, thisArg, args, true);
  26. }
  27. public off(event: string|number, cb: Function, thisArg?: any, once?: boolean) {
  28. let handlers = this._handlersMap[event];
  29. if (!handlers) {
  30. return;
  31. }
  32. for (let i = 0; i < handlers.length; ++i) {
  33. let h = handlers[i];
  34. if (h.cb == cb && h.thisArg == thisArg && h.once == once) {
  35. handlers.splice(i, 1);
  36. return;
  37. }
  38. }
  39. }
  40. public clearAll(event?: string|number) {
  41. if (event||event == 0) {
  42. delete this._handlersMap[event];
  43. }
  44. else {
  45. this._handlersMap = {};
  46. }
  47. }
  48. public emit(event: string|number, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) {
  49. let handlers = this._handlersMap[event];
  50. if (!handlers || !handlers.length) {
  51. return;
  52. }
  53. let args = [arg0, arg1, arg2, arg3, arg4];
  54. for (let i = 0; i < handlers.length; ++i) {
  55. let h = handlers[i];
  56. if (h.event == event) {
  57. h.cb.apply(h.thisArg, args);
  58. }
  59. }
  60. }
  61. }