Source: eventer/Eventer.js

  1. /* eslint prefer-rest-params: 0 */
  2. import {Utils} from '../utils/Utils';
  3. /**
  4. * jcc2d的事件对象的类
  5. *
  6. * @class
  7. * @memberof JC
  8. */
  9. function Eventer() {
  10. /**
  11. * 事件监听列表
  12. *
  13. * @member {Object}
  14. * @private
  15. */
  16. this.listeners = {};
  17. }
  18. /**
  19. * 事件对象的事件绑定函数
  20. *
  21. * @param {String} type 事件类型
  22. * @param {Function} fn 回调函数
  23. * @return {this}
  24. */
  25. Eventer.prototype.on = function(type, fn) {
  26. if (!Utils.isFunction(fn)) return;
  27. this.interactive = true;
  28. this.listeners[type] = this.listeners[type] || [];
  29. this.listeners[type].push(fn);
  30. return this;
  31. };
  32. /**
  33. * 事件对象的事件解绑函数
  34. *
  35. * @param {String} type 事件类型
  36. * @param {Function} fn 注册时回调函数的引用
  37. * @return {this}
  38. */
  39. Eventer.prototype.off = function(type, fn) {
  40. if (Utils.isUndefined(this.listeners[type])) return;
  41. const cbs = this.listeners[type] || [];
  42. let i = cbs.length;
  43. if (i > 0) {
  44. if (fn) {
  45. while (i--) {
  46. if (cbs[i] === fn) {
  47. cbs.splice(i, 1);
  48. }
  49. }
  50. } else {
  51. cbs.length = 0;
  52. }
  53. }
  54. return this;
  55. };
  56. /**
  57. * 事件对象的一次性事件绑定函数
  58. *
  59. * @param {String} type 事件类型
  60. * @param {Function} fn 回调函数
  61. * @return {this}
  62. */
  63. Eventer.prototype.once = function(type, fn) {
  64. if (!Utils.isFunction(fn)) return;
  65. const This = this;
  66. const cb = function(ev) {
  67. if (fn) fn(ev);
  68. This.off(type, cb);
  69. };
  70. this.on(type, cb);
  71. return this;
  72. };
  73. /**
  74. * 事件对象的触发事件函数
  75. *
  76. * @param {String} type 事件类型
  77. * @param {JC.InteractionData} ev 事件数据
  78. */
  79. Eventer.prototype.emit = function(type) {
  80. if (Utils.isUndefined(this.listeners[type])) return;
  81. const cbs = this.listeners[type] || [];
  82. const cache = cbs.slice(0);
  83. const reset = [];
  84. for (let j = 1; j < arguments.length; j++) {
  85. reset.push(arguments[j]);
  86. }
  87. let i;
  88. for (i = 0; i < cache.length; i++) {
  89. cache[i].apply(this, reset);
  90. }
  91. };
  92. export {Eventer};