类似于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)
}
})
}
}