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)
    
  • 相关阅读:
    电源
    SM2947
    网表
    cadence设计思路
    青山依旧在,几度夕阳红
    乐观锁与悲观锁
    笔记
    强弱软虚引用
    缓存相关
    dubbo
  • 原文地址:https://www.cnblogs.com/dshvv/p/15219784.html
Copyright © 2011-2022 走看看