-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent-bus.js
57 lines (51 loc) · 1.08 KB
/
event-bus.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
class EventBus {
constructor() {
this._events = new Map()
}
on(name, fn) {
if (!this._events.get(name)) {
this._events.set(name, fn)
}
}
emit(name, data) {
let fn = this._events.get(name)
if (fn) {
fn.call(this, data)
} else {
throw Error(`not found ${name} function`)
}
}
//如果是多个监听 fn存成数组的形式
}
class EventEmitter {
constructor() {
this._events = new Map()
}
on(name, fn) {
if (!this._events.get(name)) {
this._events.set(name, [fn])
} else {
this._events.get(name).push(fn)
}
}
off(name, fn) {
let fns = this._events.get(name)
if (fns) {
let index = fns.findIndex(item => item === fn)
if (index >= 0) {
fns.splice(index, 1)
}
}
}
emit(name, once = false, ...args) {
if (this._events.get(name)) {
let fns = this._events.get(name).slice(0)
fns.forEach(fn => fn.call(this, ...args))
if (once) {
this._events.delete(name)
}
} else {
throw Error(`not found ${name} function`)
}
}
}