UNPKG

2.76 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var factories = [];
4factories[0] = function () {
5 return function dispatcher0() { };
6};
7factories[1] = function (callback, context) {
8 if (typeof (context) === 'undefined')
9 return callback;
10 return function dispatcher1(payload) {
11 callback(payload, context);
12 };
13};
14function getFactory(handlerCount) {
15 if (!factories[handlerCount])
16 factories[handlerCount] = compileFactory(handlerCount);
17 return factories[handlerCount];
18}
19function 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}
30var 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}());
76exports.default = Event;