-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventemitter.js
49 lines (49 loc) · 1.22 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
47
48
49
let EventEmitter = (() => {
let eventHandlers = new WeakMap();
class EventEmitter {
constructor(...knownEvents) {
let handlers = new Map();
for (let event of knownEvents) {
handlers.set(event, null);
}
eventHandlers.set(this, handlers);
}
on(event, handler) {
let handlers = eventHandlers.get(this).get(event);
if (handlers === null) {
handlers = new Set();
eventHandlers.get(this).set(event, handlers);
}
if (handlers) {
handlers.add(handler);
}
return this;
}
off(event, handler) {
let handlers = eventHandlers.get(this).get(event);
if (handlers) {
handlers.delete(handler);
}
return this;
}
static emit(obj, event, ...args) {
let handlers = eventHandlers.get(obj).get(event);
if (handlers && handlers.size > 0) {
// Copy for consistency in case one handler removes another
let currentHandlers = new Set(handlers);
for (let handler of currentHandlers) {
try {
handler(...args);
} catch (e) {
console.warn('Error thrown from event handler:', e);
}
}
}
}
static hasListener(obj, event) {
let handlers = eventHandlers.get(obj).get(event);
return handlers && handlers.size > 0;
}
}
return EventEmitter;
})();