js发布订阅模式实现eventBus
2021-03-02 23:27
标签:push class name eventbus handler rop ons ntb eve 使用示例: js发布订阅模式实现eventBus 标签:push class name eventbus handler rop ons ntb eve 原文地址:https://www.cnblogs.com/BlueCc/p/14308824.htmlclass EventBus {
constructor(){}
handlerBus={}
//注册
$on(eventName,handler){
if(!this.handlerBus.hasOwnProperty(eventName)){
this.handlerBus[eventName] = []
}
this.handlerBus[eventName].push(handler)
}
//触发
$emit(eventName,handlerParams){
if(!this.handlerBus.hasOwnProperty(eventName)){
return new Error(‘未注册该事件‘)
}
const eventHandlers = this.handlerBus[eventName]
for(let i = 0;i
const EventBusObj = new EventBus()
const f1=(p)=>{
console.log(‘f1‘)
console.log(p)
}
const f2=(p)=>{
console.log(‘f2‘)
console.log(p)
}
//注册
EventBusObj.$on(‘event1‘,f1)
EventBusObj.$on(‘event1‘,f2)
//触发
EventBusObj.$emit(‘event1‘,{a:1})
//移除event1的f1方法
EventBusObj.$remove(‘event1‘,f1)
文章标题:js发布订阅模式实现eventBus
文章链接:http://soscw.com/index.php/essay/59250.html