-
Notifications
You must be signed in to change notification settings - Fork 1
/
eventemitter.js
46 lines (40 loc) · 1.26 KB
/
eventemitter.js
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
var _ = require("./misc");
var assert = require("./assert");
function EventEmitter() {
this.__listeners = {};
}
EventEmitter.prototype.addEventListener = function(evt, fn) {
assert(typeof fn == "function", "eventemitter: second argument should be a function");
if (!this.__listeners[evt]) this.__listeners[evt] = [];
this.__listeners[evt].push(fn);
};
EventEmitter.prototype.removeEventListener = function(evt, fn) {
if (arguments.length === 0) {
this.__listeners = {};
return;
}
if (!this.__listeners.hasOwnProperty(evt)) return;
if (arguments.length === 1) {
delete this.__listeners[evt];
return;
}
var listeners = this.__listeners[evt];
var index = listeners.indexOf(fn);
if (~index) listeners.splice(index, 1);
if (!listeners.length) delete this.__listeners[evt];
};
EventEmitter.prototype.trigger = function(evt, arg) {
if (!this.__listeners.hasOwnProperty(evt)) return;
var listeners = this.__listeners[evt].slice();
_.each(listeners, listener => {
try {
listener(arg);
} catch(e) {
console.error(e, e.stack);
}
});
};
// aliases
EventEmitter.prototype.on = EventEmitter.prototype.addEventListener;
EventEmitter.prototype.off = EventEmitter.prototype.removeEventListener;
module.exports = EventEmitter;