0%

事件总线

事件总线(EventBus)

事件总线是一种观察者模式,包括三个角色

  • 发布者:发布事件
  • 订阅者:订阅事件,并进行响应
  • 时间总线:无论发布者还是订阅者都通过事件总线作为中台

目的:开发过程中不同组件之间通信 组件通信

事件总线的实现

  • 事件的监听方法on
  • 事件的发射方法emit
  • 事件的取消监听off

由于一个EventBus对象会在多个地方使用,所以将其中的属性和函数定义为静态的

也可采用实例化的方法,那样需要把这个实例放在全局变量中,如在React在根节点定义Context

EventBus的实现:

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
class EventBus{
static eventMap = {}

static on(eventName, eventFn){
(this.eventMap[eventName] || (this.eventMap[eventName] = []))&&this.eventMap[eventName].push(eventFn)
}
static emit(eventName, ...args){
if(!this.eventMap[eventName]){
console.log(eventName,"没有监听")
return
}
for(let fun of this.eventMap[eventName]){
fun.apply(this,args)
}
}
static off(eventName, eventFn){
let eventFns = this.eventMap[eventName]
if(!eventFns){
console.log(eventName,"没有监听")
return
}
for(let i=0;i<eventFns.length;i++){
if(eventFn===eventFns[i]){
eventFns.splice(i,1)
console.log(this.eventMap)
break
}
}
}
}

EventBus的使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let function1 = function(...args){
console.log("function1", this.eventMap, args)
}
let function2 = function(...args){
console.log("function2", this.eventMap, args)
}

EventBus.on("click",function1)
EventBus.on("click",function2)

EventBus.on("click2",function1)

EventBus.emit("click", "oww", "18")
EventBus.emit("click2", "oww1", "22")

EventBus.off("click",function2)

image-20230325134633475