-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent-emitter.ts
More file actions
54 lines (50 loc) · 1.21 KB
/
event-emitter.ts
File metadata and controls
54 lines (50 loc) · 1.21 KB
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
export default class EventEmitter {
listeners: Map<string,any>
constructor() {
this.listeners = new Map()
}
/**
* @param {string} eventName
* @param {Function} listener
* @returns {EventEmitter}
*/
on(eventName: string, listener: Function) {
const current = this.listeners.get(eventName) || []
current.push(listener)
this.listeners.set(eventName, current)
return this
}
/**
* @param {string} eventName
* @param {Function} listener
* @returns {EventEmitter}
*/
off(eventName: string, listener: Function) {
const allListeners = this.listeners.get(eventName)
if (!allListeners) { return this }
const newListeners = []
let removedAlready = false
for (const l of allListeners) {
if (l === listener && !removedAlready) {
removedAlready = true;
continue;
}
newListeners.push(l);
}
this.listeners.set(eventName, newListeners)
return this
}
/**
* @param {string} eventName
* @param {...any} args
* @returns {boolean}
*/
emit(eventName, ...args) {
const listeners = this.listeners.get(eventName)
if (!listeners || listeners.length < 1) {
return false
}
listeners.forEach(l => l.apply(this, args))
return true
}
}