EventEmitter的实现

ES6的实现

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
export class EventEmitter {
constructor () {
this.listenerList = {}
}
on (e, cb) {
const cbs = this.listenerList[e] || []
if (typeof cb !== 'function') {
throw new TypeError(`${cb} is not a function`)
} else {
cbs.push(cb)
}
this.listenerList[e] = cbs
}
emit (e) {
const cbs = this.listenerList[e]
const restArgs = Array.prototype.slice.call(arguments, 1)
if (cbs && cbs.length) {
cbs.forEach((cb) => {
cb(...restArgs)
})
}
}
off (e, fn) {
const cbs = this.listenerList[e]
if (cbs && cbs.length) {
if (fn && cbs.includes(fn)) {
const index = cbs.indexOf(fn)
cbs.splice(index, 1)
} else if (!fn) {
delete this.listenerList[e]
}
}
}
}