事件总线-(EventBus)

自定义事件总线

自定义事件总线属于一种观察者模式,其中包括三个角色:

口发布者(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)
复制代码

 

posted @   KooTeam  阅读(73)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示