• 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)    
    

      

  • 相关阅读:
    xampp+vscode开发php的配置流程
    如何开始学习以太坊及区块链
    java动态生成带下拉框的Excel导入模板
    汉字转拼音
    Git+Gradle+Eclipse构建项目
    test
    MacOS这idea快捷键
    HashMap扩容全过程
    NIO理解
    详解MySQL 内连接、外连接、左连接、右连接
  • 原文地址:https://www.cnblogs.com/BlueCc/p/14308824.html
Copyright © 2020-2023  润新知