zoukankan      html  css  js  c++  java
  • 2021发布订阅模式

    两年看还费事 如今徒手 不百度 没卡的给写出来了 自己都不信
    真的是功到自然成啊

    /*
    * 发布订阅
    **/
    class Pubsub{
        static instance = null;
    
        // 单例
        static getInstance(){
            if(Pubsub.instance == null){
                Pubsub.instance = new Pubsub;
            }
            return Pubsub.instance;
        }
    
        // 注册的事件和处理器关联集合
        eventAndHandel = {};
    
        // 触发  
        emit(eventName, params){
           if(this.eventAndHandel.hasOwnProperty(eventName)){
            this.eventAndHandel[eventName].forEach(hander => {
                hander(params)
            });
           }
        }
    
        // 注册or订阅
        on(eventName, cbc){
            if(!this.eventAndHandel.hasOwnProperty(eventName)){
                this.eventAndHandel[eventName] = [cbc]
            }else{
                this.eventAndHandel[eventName].push(cbc)
            }
        }
    }
    
    const pubsub = Pubsub.getInstance();
    // 测试
    pubsub.on('one',(res)=>{
        console.log('第一套测试:'+res);
    });
    pubsub.emit('one',1);
    pubsub.emit('one',2)
    
    // 再测试
    pubsub.on('two',(res)=>{
        console.log('第二套测试:'+res);
    });
    pubsub.emit('two',3);
    pubsub.emit('two',4)
    
  • 相关阅读:
    等价表达式
    读入字符串
    n以内质数占的比例
    图论——最小生成树_prim
    搜索
    图论——最小生成树
    线段树模板
    WC总结
    三练斜率优化
    斜率优化技巧——换个角度思考
  • 原文地址:https://www.cnblogs.com/dshvv/p/15219784.html
Copyright © 2011-2022 走看看