EventEmitter
EventEmitter 的核心就是事件触发与事件监听器功能的封装
发布 + 订阅
DOM 的事件机制就是发布订阅模式最常见的实现,这大概是前端最常用的编程模型了,监听某事件,当该事件发生时,监听该事件的监听函数被调用户。
EventEmitter 方法主要包含了 on,emit,once,off 方法。
class EventEmitter {
constructor() {
this.events = Object.create(null)
}
on(name, fn) {
if (!this.events[name]) {
this.events[name] = []
}
this.events[name].push(fn)
return this
}
emit(name, ...args) {
if (!this.events[name]) {
return this
}
const fns = this.events[name]
fns.forEach(fn => fn.call(this, ...args))
return this
}
off(name, fn) {
if (!this.events[name]) {
return this
}
if (!fn) {
this.events[name] = null
return this
}
const index = this.events[name].indexOf(fn)
this.events[name].splice(index, 1)
return this
}
once(name, fn) {
const only = () => {
fn.apply(this, arguments)
this.off(name, only)
}
this.on(name, only)
return this
}
}
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
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
Vue 中非父子组件组件通信
在 Vue 中不同组件之间通讯,有一种解决方案叫Event Bus,这其实就是发布订阅模式的实现,非常简单好用。
使用 Event Bus 进行跨组件消息传递很棒,但是,当事件非常多的时候,Event Bus 上的事件就会难以维护,这与使用全局变量一样一个道理。变量能局部的,就尽量不要放到全局,同样 Event Bus 上的事件也是越少越好