-
Notifications
You must be signed in to change notification settings - Fork 47k
/
events.js
75 lines (68 loc) · 1.9 KB
/
events.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
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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export default class EventEmitter<Events: Object> {
listenersMap: Map<string, Array<Function>> = new Map();
addListener<Event: $Keys<Events>>(
event: Event,
listener: (...$ElementType<Events, Event>) => any,
): void {
const listeners = this.listenersMap.get(event);
if (listeners === undefined) {
this.listenersMap.set(event, [listener]);
} else {
const index = listeners.indexOf(listener);
if (index < 0) {
listeners.push(listener);
}
}
}
emit<Event: $Keys<Events>>(
event: Event,
...args: $ElementType<Events, Event>
): void {
const listeners = this.listenersMap.get(event);
if (listeners !== undefined) {
if (listeners.length === 1) {
// No need to clone or try/catch
const listener = listeners[0];
listener.apply(null, args);
} else {
let didThrow = false;
let caughtError = null;
const clonedListeners = Array.from(listeners);
for (let i = 0; i < clonedListeners.length; i++) {
const listener = clonedListeners[i];
try {
listener.apply(null, args);
} catch (error) {
if (caughtError === null) {
didThrow = true;
caughtError = error;
}
}
}
if (didThrow) {
throw caughtError;
}
}
}
}
removeAllListeners(): void {
this.listenersMap.clear();
}
removeListener(event: $Keys<Events>, listener: Function): void {
const listeners = this.listenersMap.get(event);
if (listeners !== undefined) {
const index = listeners.indexOf(listener);
if (index >= 0) {
listeners.splice(index, 1);
}
}
}
}