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)
posted @ 2021-09-02 17:31  丁少华  阅读(69)  评论(0编辑  收藏  举报