标签:push class name eventbus handler rop ons ntb eve
class 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<eventHandlers.length;i++){ eventHandlers[i](handlerParams) } } //触发一次 $onece(eventName,handlerParams){ this.$emit(eventName,handlerParams) this.$remove(eventName) } //移除 $remove(eventName,handler){ if(!this.handlerBus.hasOwnProperty(eventName)){ return new Error(‘未注册该事件‘) } if(!handler){ //如果没指定移除的子handler 则移除整个eventName Reflect.defineProperty(this.handlerBus,eventName) return } //如果指定了handler const eventHandlers = this.handlerBus[eventName] const handlerIndex = eventHandlers.findIndex(event=>event === handler) if(handlerIndex === -1){ return new Error(‘未绑定该事件‘) } this.handlerBus[eventName].splice(handlerIndex,1) if(this.handlerBus[eventName].length === 0)Reflect.defineProperty(this.handlerBus,eventName) } } export default EventBus
使用示例:
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)
标签:push class name eventbus handler rop ons ntb eve
原文地址:https://www.cnblogs.com/BlueCc/p/14308824.html