js釋出訂閱模式實現eventBus
阿新 • • 發佈:2021-01-21
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)