Event.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var factories = [];
  4. factories[0] = function () {
  5. return function dispatcher0() { };
  6. };
  7. factories[1] = function (callback, context) {
  8. if (typeof (context) === 'undefined')
  9. return callback;
  10. return function dispatcher1(payload) {
  11. callback(payload, context);
  12. };
  13. };
  14. function getFactory(handlerCount) {
  15. if (!factories[handlerCount])
  16. factories[handlerCount] = compileFactory(handlerCount);
  17. return factories[handlerCount];
  18. }
  19. function compileFactory(handlerCount) {
  20. var src = 'return function dispatcher' + handlerCount + '(payload) {\n';
  21. var argsHandlers = [], argsContexts = [];
  22. for (var i = 0; i < handlerCount; i++) {
  23. argsHandlers.push('cb' + i);
  24. argsContexts.push('ctx' + i);
  25. src += ' cb' + i + '(payload, ctx' + i + ');\n';
  26. }
  27. src += '};';
  28. return new (Function.bind.apply(Function, [void 0].concat(argsHandlers.concat(argsContexts), [src])))();
  29. }
  30. var Event = /** @class */ (function () {
  31. function Event() {
  32. this.hasHandlers = false;
  33. this._handlers = [];
  34. this._contexts = [];
  35. this._createDispatcher();
  36. }
  37. Event.prototype.addHandler = function (handler, context) {
  38. if (!this.isHandlerAttached(handler, context)) {
  39. this._handlers.push(handler);
  40. this._contexts.push(context);
  41. this._createDispatcher();
  42. this._updateHasHandlers();
  43. }
  44. return this;
  45. };
  46. Event.prototype.removeHandler = function (handler, context) {
  47. var idx = this._getHandlerIndex(handler, context);
  48. if (typeof (idx) !== 'undefined') {
  49. this._handlers.splice(idx, 1);
  50. this._contexts.splice(idx, 1);
  51. this._createDispatcher();
  52. this._updateHasHandlers();
  53. }
  54. return this;
  55. };
  56. Event.prototype.isHandlerAttached = function (handler, context) {
  57. return typeof (this._getHandlerIndex(handler, context)) !== 'undefined';
  58. };
  59. Event.prototype._updateHasHandlers = function () {
  60. this.hasHandlers = !!this._handlers.length;
  61. };
  62. Event.prototype._getHandlerIndex = function (handler, context) {
  63. var handlerCount = this._handlers.length;
  64. var idx;
  65. for (idx = 0; idx < handlerCount; idx++) {
  66. if (this._handlers[idx] === handler && this._contexts[idx] === context)
  67. break;
  68. }
  69. return idx < handlerCount ? idx : undefined;
  70. };
  71. Event.prototype._createDispatcher = function () {
  72. this.dispatch = getFactory(this._handlers.length).apply(this, this._handlers.concat(this._contexts));
  73. };
  74. return Event;
  75. }());
  76. exports.default = Event;