0%

手写一个事件中心

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
class EventEmitter {
constructor() {
this.events = Object.create(null)
}
emit(name, ...args) {
const cbs = this.events[name]
if (cbs) {
for (const cb of cbs) {
cb(...args)
}
}
}
on(name, fn) {
if (Array.isArray(name)) {
for (const n of name) {
this.on(n, fn)
}
} else {
;(this.events[name] || (this.events[name] = [])).push(fn)
}
}
once(name, fn) {
const that = this
function on(...args) {
that.off(name, on)
fn(...args)
}
on.fn = fn
this.on(name, on)
}
off(name, fn) {
if (name === void 0) {
this.events = Object.create(null)
}
if (Array.isArray(name)) {
for (const n of name) {
this.off(n, fn)
}
return
}
const cbs = this.events[name] || []
if (!fn) {
this.events[name] = null
return
}
for (const i in cbs) {
const cb = cbs[i]
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1)
return
}
}
}
}