zoukankan      html  css  js  c++  java
  • js发布订阅模式实现eventBus

    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)    
    

      

  • 相关阅读:
    redis命令参考(四) set集合
    redis命令参考(三) List列表相关
    redis命令参考(二)
    redis命令参考(一) SortedSet相关
    insert_into_on_dumplicate_key
    laravel深入分析
    开发中GBK+UTF8编码的处理
    ajax封装调用
    linux正则表达式的用法
    linux 如何保证使程序后台运行(nohup &)
  • 原文地址:https://www.cnblogs.com/BlueCc/p/14308824.html
Copyright © 2011-2022 走看看