-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventEmitter.js
55 lines (49 loc) · 1.18 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
class EventEmitter {
constructor() {
this.events = {}
}
isValidListener(listener) {
if (typeof listener === 'function') {
return true
} else if (listener && typeof listener === 'object') {
this.isValidListener(listener.listener)
} else {
return false
}
}
on(type, listener) {
if (!this.isValidListener(listener)) {
throw new TypeError('listener shoule be a funciton')
}
const listeners = this.events[type] || []
const listenerFn = typeof listener === 'function' ? listener : listener.listener
if (!listeners.includes(listenerFn)) {
listeners.push({
listener: listenerFn,
once: false
})
}
}
once(type, listener) {
this.on(type, {
listener,
once: true
})
}
off(type, listener) {
const listeners = this.events[type]
const index = listeners.findIndex(item => item.listener === listener)
if (index > -1) {
listeners.splice(index, 1)
}
}
emit(type) {
const listeners = this.events[type] || []
listeners.forEach(listener => {
listener.listener()
if (listener.once) {
this.off(type, listener.listener)
}
})
}
}