BaseEvent.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. function BaseEvent() {}
  2. BaseEvent.prototype = {
  3. triggerEvent: function (eventName, args) {
  4. if (this._cbs[eventName]) {
  5. var callbacks = this._cbs[eventName];
  6. for (var i = 0; i < callbacks.length; i += 1) {
  7. callbacks[i](args);
  8. }
  9. }
  10. },
  11. addEventListener: function (eventName, callback) {
  12. if (!this._cbs[eventName]) {
  13. this._cbs[eventName] = [];
  14. }
  15. this._cbs[eventName].push(callback);
  16. return function () {
  17. this.removeEventListener(eventName, callback);
  18. }.bind(this);
  19. },
  20. removeEventListener: function (eventName, callback) {
  21. if (!callback) {
  22. this._cbs[eventName] = null;
  23. } else if (this._cbs[eventName]) {
  24. var i = 0;
  25. var len = this._cbs[eventName].length;
  26. while (i < len) {
  27. if (this._cbs[eventName][i] === callback) {
  28. this._cbs[eventName].splice(i, 1);
  29. i -= 1;
  30. len -= 1;
  31. }
  32. i += 1;
  33. }
  34. if (!this._cbs[eventName].length) {
  35. this._cbs[eventName] = null;
  36. }
  37. }
  38. },
  39. };
  40. export default BaseEvent;