自定义事件总线
自定义事件总线属于一种观察者模式,其中包括三个角色:
口发布者(Publisher):发出事件(Event);
口订阅者(Subscriber):订阅事件(Event),并且会进行响应(Handler);
口事件总线(EventBus):无论是发布者还是订阅者都是通过事件总线作为中台的;
当然我们可以选择一些第三方的库:
口Vue2默认是带有事件总线的功能;
口Vue3中推荐一些第三方库,比如mitt;
当然我们也可以实现自己的事件总线:
口事件的监听方法on;口事件的发射方法emit;口事件的取消监听off;
1 class EventBus{
2 constructor(){
3 this.eventBus={}
4 }
5 on(eventName,eventCallback,thisArg){
6 let handlers=this.eventBus[eventName]
7 if(!handlers){
8 handlers=[]
9 this.eventBus[eventName]=handlers
10 }
11 handlers.push({
12 eventCallback,
13 thisArg
14 })
15 }
16 off(eventName,eventCallback){
17 const handlers=this.eventBus[eventName]
18 if(!handlers)return
19 const newHandlers=[...handlers]
20 for(let i=0;i<newHandlers.length;i++){
21 const handler=newHandlers[i]
22 if(handler.eventCallback===eventCallback){
23 const index=handlers.indexOf(handler)
24 handlers.splice(index,1)
25 }
26 }
27 }
28 emit(eventName,...payload){
29 const handlers=this.eventBus[eventName]
30 if(!handlers)return
31 handlers.forEach(handler => {
32 handler.eventCallback.apply(handler.thisArg,payload)
33 });
34 }
35 }
36 const eventBus=new EventBus()
37
38 //main.js
39 eventBus.on('abc',function(){
40 console.log('watch abc1',this)
41 },{name:'koo'})
42 const handleCallback=function(){
43 console.log('watch abc2',this)
44 }
45 eventBus.on('abc',handleCallback,{name:'koo'})
46
47 //utils.js
48 eventBus.emit('abc',123)
49
50 //移除监听
51 eventBus.off('abc',handleCallback)
52 eventBus.emit('abc',123)