现在位置: 首页  >  编程技术  >  JS
用 BroadcastChannel 实现的一个消息总线
0 806

用 BroadcastChannel 实现的一个消息总线

const msgBus={
    BcList:[],
    getBcByName(name){
        for (let i = 0; i < this.BcList.length; i++) {
            if (this.BcList[i].name==name){
                return this.BcList[i];
            }
        }
        return false;
    },
    join(name){
        let BC=this.getBcByName(name);
        if (BC==false){
            BC=new BroadcastChannel(name);
            this.BcList.push(BC);
        }
        return BC;
    },
    on(name,callback){
        let BC=this.join(name);
        BC.onmessage=callback;
    },
    emit(name,msg){
        let BC=this.join(name);
        BC.postMessage(msg);
    },
    _emit(name,msg){
        let BC=new BroadcastChannel(name);
        BC.postMessage(msg);
        BC.close();
    },
    off(name=''){
        let BC={};
        if (name==''){
            for (let i = 0; i < this.BcList.length; i++) {
                BC=this.BcList[i];
                BC.close();
            }
            this.BcList=[];
        }else{
            BC=this.getBcByName(name);
            this.BcList.splice(this.BcList.indexOf(BC),1);
        }
    },
}

msgBus.on('a',(e)=>{
    console.log(e)
})

msgBus.emit('a','abc')  // 当前页面不触发 onmessage ,因为是同一个对象发出的消息,该对象不执行自己的消息
msgBus._emit('a','abc')  // 当前页面会触发 onmessage ,因为是用了个新对象发出的消息

msgBus.off() // 关闭当前页面所有BroadcastChannel对象
msgBus.off('a') // 关闭当前页面名为a的BroadcastChannel对象


 评论
 站内搜索