forked from yeyan1996/practical-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventEmitter.js
62 lines (51 loc) · 1.23 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
56
57
58
59
60
61
62
//发布订阅
class EventEmitter {
constructor() {
this.subs = {}
}
on(event, cb) {
if (!this.subs[event]) {
this.subs[event] = []
this.subs[event].push(cb)
}
}
trigger(event, options) {
if (this.subs[event]) {
this.subs[event].forEach(cb => {
cb(options)
})
}
}
once(event, onceCb) {
const cb = (...rest) => {
let res = onceCb.apply(null, rest)
this.off(event, onceCb)
return res
}
if (!this.subs[event]) {
this.subs[event] = []
this.subs[event].push(cb)
}
}
off(event, offCb) {
if (this.subs[event]) {
let index = this.subs[event].findIndex(cb => cb === offCb)
this.subs[event].splice(index, 1)
if (!this.subs[event].length) delete this.subs[event]
}
}
}
let dep = new EventEmitter()
let cb = function () {
console.log('handleClick')
}
let cb2 = function () {
console.log('handleMouseover')
}
dep.on('click', cb)
dep.trigger('click')
dep.off('click', cb)
dep.trigger('click')
dep.once('mouseover', cb2)
dep.trigger('mouseover')
dep.trigger('mouseover')