-
Notifications
You must be signed in to change notification settings - Fork 0
/
event-emitter.js
75 lines (63 loc) · 1.81 KB
/
event-emitter.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
class EventEmitter {
constructor() {
this.listeners = new Map()
}
on(event, cb, once = false) {
if (!this.listeners.has(event)) {
this.listeners.set(
event,
{
callbacks: new Set, // use Set to register callback once
once,
}
)
}
this.listeners.get(event).callbacks.add(cb)
return this // support chaining
}
once(event, cb) {
const once = true
this.on(event, cb, once)
}
off(event, cb) {
if (!this.listeners.has(event)) return
this.listeners.get(event).callbacks.delete(cb)
return this
}
// TODO: check use cases for args and chaining, it looks dumb
emit(event, ...args) {
// check unregistered event
if (!this.listeners.has(event)) return
const {callbacks, once} = this.listeners.get(event)
for (const cb of callbacks) {
// support callback args
cb(...args)
}
if (once) {
this.listeners.delete(event)
}
return this
}
}
const emitter = new EventEmitter()
function one () {console.log('one')}
function two () {console.log('two')}
function three () {console.log('three')}
function doubleAndPrint (num, str) {console.log(num * 2, str)}
emitter.on('run', one)
emitter.on('run', two)
emitter.on('run', two)
emitter.on('run', three)
emitter.on('run', doubleAndPrint)
emitter.off('run', three)
emitter.on('chain', three)
.on('chain', two)
.on('chain', one)
.on('other', doubleAndPrint)
.emit('other', 5 ,7)
emitter.emit('run', 5, 7)
emitter.emit('chain')
emitter.once('onlyOnce', two)
emitter.emit('onlyOnce')
emitter.emit('onlyOnce')
emitter.emit('onlyOnce')