-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDispatcher.js
105 lines (92 loc) · 2.27 KB
/
Dispatcher.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import Event from './events/Event.js';
const listenersMap = Symbol('listenersMap');
export default class Dispatcher {
constructor() {
this[listenersMap] = new Map();
}
/**
* Dispatches an event to all registered listeners.
*
* @param {string} eventName
* @param {Event} event
*
* @returns {Event}
*/
async dispatch(eventName, event = null) {
const theEvent = event || new Event();
const listeners = this.getListeners(eventName);
await this.doDispatch(listeners, eventName, theEvent);
return theEvent;
}
/**
* Triggers the listeners of an event.
*
* This method can be overridden to add functionality
* that is executed for each listener.
*
* @protected
*
* @param {function[]} listeners
* @param {string} eventName
* @param {Event} event
*/
async doDispatch(listeners, eventName, event) {
const l = listeners.length;
for (let i = 0; i < l; i += 1) {
if (event.isPropagationStopped()) {
break;
}
await listeners[i](event, eventName, this);
}
}
/**
* Gets the listeners of a specific event.
*
* @param {string} eventName
*
* @returns {function[]}
*/
getListeners(eventName) {
if (!this.hasListeners(eventName)) {
return [];
}
return Array.from(this[listenersMap].get(eventName).keys());
}
/**
* Checks whether an event has any registered listeners.
*
* @param {string} eventName
*
* @returns {boolean}
*/
hasListeners(eventName) {
if (!this[listenersMap].has(eventName)) {
return false;
}
return this[listenersMap].get(eventName).size > 0;
}
/**
* Adds an event listener that listens on the specified events.
*
* @param {string} eventName
* @param {function} listener
*/
addListener(eventName, listener) {
if (!this[listenersMap].has(eventName)) {
this[listenersMap].set(eventName, new Map());
}
this[listenersMap].get(eventName).set(listener, true);
}
/**
* Removes an event listener from the specified event.
*
* @param {string} eventName
* @param {function} listener
*/
removeListener(eventName, listener) {
if (!this[listenersMap].has(eventName)) {
return;
}
this[listenersMap].get(eventName).delete(listener);
}
}