当前位置:网站首页>微信小程序自己实现一个全局事件总线
微信小程序自己实现一个全局事件总线
2022-07-23 17:20:00 【大鲤余】
类似于Vue的全局事件总线
遇到问题:自己的小项目中用户点击修改头像,首页的头像需要同步修改。
思路
- 首先给app跟实例绑定一个属性$bus
- 然后造一个数组存放我们的事件
- emit发布事件,接受三个参数(事件名,函数,和this指向) 我这里由于小项目自己练习,因此没有做参数合法的校验以及event内部是否重复的判断
- on进行订阅自定义事件,由于已经绑定过this因此直接执行
- off用来取消事件
export class Bus{
constructor(){
this.event = []
}
emit = (eventName,fn,that)=>{
this.event.push({
[eventName]:fn.bind(that)
})
}
on = (eventName,params)=>{
this.event.forEach((v,index)=>{
if(v[eventName]){
v[eventName](params)
console.log('自定义事件执行了');
}else{
console.error("没有找到自定义事件",eventName)
}
})
}
off = (eventName)=>{
this.event.forEach((v,index)=>{
if(v[eventName]){
this.event.splice(index,1)
}
})
}
}
边栏推荐
- Terminal command (all)
- Testing scheme of granite dielectric constant by network
- 【论文阅读】GETNext: Trajectory Flow Map Enhanced Transformer for Next POI Recommendation
- Tree learning summary
- MySQL [knowing and mastering one article is enough]
- .NET Core 实现后台任务(定时任务)Longbow.Tasks 组件(三)
- Shell
- LeetCode 0131. 分割回文串
- FPGA基于spi的flash读写
- VB connecting access database customization
猜你喜欢

Learn and understand Architecture Design from business development

【机器学习】吴恩达:终生学习

Tcl 语言之Synopsys Tcl篇(3)(数字IC)

Lendingclub loan status business details current, charge off, issued, full paid, grace period
![[2018] [paper notes] graphene FET and [2] - Preparation and transfer of graphene](/img/32/c6e4af95baf322adf06bd8ee741b67.png)
[2018] [paper notes] graphene FET and [2] - Preparation and transfer of graphene

The first layer of OSI model: physical layer, the cornerstone of existence!

Navigation component of jetpack compose uses

FPGA实现IIC协议(二)之IIC总线的FPGA实现(单次读写驱动)

1259. Disjoint handshake dynamic programming

Mbio | the sun Chaomin formation of Ocean Institute has verified in situ the new pathway of microbial mediated elemental sulfur formation in the deep sea
随机推荐
作为一名后台开发人员,你必须知道的两种过滤器
使用 frp 实现内网穿透
CTF misc learning summary "suggestions collection"
【C语言】程序环境和预处理
moxa串口服务器型号,moxa串口服务器产品配置说明
SQL 语句练习
Google正在改进所有产品中的肤色表现 践行“图像公平”理念
【论文阅读】GETNext: Trajectory Flow Map Enhanced Transformer for Next POI Recommendation
[the whole process of Game Modeling and model production] create the game soldier character with ZBrush
quota的使用方法
Integer and = = compare
398. Random number index hash table method
界面设计四大原则
DP问题大合集
Conception de l'interface UART basée sur la FPGA
Figure learning summary
Perl语言简述
1259. 不相交的握手 动态规划
PHP file lock lottery to prevent concurrency
C language small project - address book (static version + dynamic version + file version)