-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventEmitter.js
89 lines (73 loc) · 1.82 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
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
class EventEmitter {
constructor() {
this.listeners = new Map()
this.nextId = 1
}
/**
* Attaches a listener.
* @param {string} event - Event name.
* @param {function} callback - Callback function.
* @returns {number} Listener ID.
*/
on(event, callback) {
if (!this.listeners.has(event)) this.listeners.set(event, new Map())
const id = this.nextId++
this.listeners.get(event).set(id, callback)
return id
}
/**
* Attaches a one-time listener.
* @param {string} event - Event name.
* @param {function} callback - Callback function.
*/
once(event, callback) {
const id = this.on(event, (...args) => {
callback(...args)
this.off(id, event)
})
}
/**
* Emits an event.
* @param {string} event - Event name.
* @param {*} data - Data to pass.
*/
emit(event, ...args) {
const listeners = this.listeners.get(event)
if (!listeners) return false
for (const callback of listeners.values()) callback(...args)
return true
}
/**
* Removes a listener.
* @param {number} id - Listener ID.
* @param {string} [event] - Event name (optional).
*/
off(id, event) {
if (event) {
const foundListeners = this.listeners.get(event)
if (foundListeners) {
foundListeners.delete(id)
if (foundListeners.size === 0) {
foundListeners.delete(event)
}
}
} else {
for (const foundListeners of this.listeners.values()) {
if (foundListeners.delete(id)) {
if (foundListeners.size === 0) {
foundListeners.delete(event)
}
break
}
}
}
}
/**
* Removes all listeners.
* @param {string} [event] - Event name (optional).
*/
offAll(event) {
event ? this.listeners.delete(event) : this.listeners.clear()
}
}
export const eventEmitter = new EventEmitter()