1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
(function() {
var Disposable, Emitter;
Disposable = require('./disposable');
module.exports = Emitter = (function() {
Emitter.prototype.isDisposed = false;
/*
Section: Construction and Destruction
*/
function Emitter() {
this.handlersByEventName = {};
}
Emitter.prototype.dispose = function() {
this.handlersByEventName = null;
return this.isDisposed = true;
};
/*
Section: Event Subscription
*/
Emitter.prototype.on = function(eventName, handler) {
var currentHandlers;
if (this.isDisposed) {
throw new Error("Emitter has been disposed");
}
if (typeof handler !== 'function') {
throw new Error("Handler must be a function");
}
if (currentHandlers = this.handlersByEventName[eventName]) {
this.handlersByEventName[eventName] = currentHandlers.concat(handler);
} else {
this.handlersByEventName[eventName] = [handler];
}
return new Disposable(this.off.bind(this, eventName, handler));
};
Emitter.prototype.off = function(eventName, handlerToRemove) {
var handler, newHandlers, oldHandlers, _i, _len;
if (this.isDisposed) {
return;
}
if (oldHandlers = this.handlersByEventName[eventName]) {
newHandlers = [];
for (_i = 0, _len = oldHandlers.length; _i < _len; _i++) {
handler = oldHandlers[_i];
if (handler !== handlerToRemove) {
newHandlers.push(handler);
}
}
return this.handlersByEventName[eventName] = newHandlers;
}
};
/*
Section: Event Emission
*/
Emitter.prototype.emit = function(eventName, value) {
var handler, handlers, _i, _len, _ref;
if (handlers = (_ref = this.handlersByEventName) != null ? _ref[eventName] : void 0) {
for (_i = 0, _len = handlers.length; _i < _len; _i++) {
handler = handlers[_i];
handler(value);
}
}
};
return Emitter;
})();
}).call(this);
|