学习 Javascript 之EventBus Map版

class EventBus {
    
    constructor() {
        //用Map存储订阅, 格式为: key="key3" value=["O2", function, "3", function] 
        this.eventMap = new Map();
        
        //每个订阅都配一个ID
        this.busid = 0;
    }
    
    //订阅  订阅名称   订阅代码  是否一次性订阅(默认否)
    dinyue(eventName, callback,isOnece=false) {
        
        //如果Map中没有这个Key就增加,值为一个空数组
        !this.eventMap.has(eventName) && this.eventMap.set(eventName,[]);
        
        //给每个事件搭配一个ID, 如果是一次性的订阅就在ID前面加一个字面O
        const cid = (isOnece ? 'O' : '') + (this.busid++);
        
        const arrEvent = this.eventMap.get(eventName);
        //在push订阅前, 把事件ID先插到前面,用于删除订阅和判断是否为一次性订阅时使用
        arrEvent.push(cid);
        arrEvent.push(callback);
        
        //返回一个数组,第一个为订阅名称,第二个为订阅ID
        return [eventName, cid];
    }
    
    //发布,订阅名称  订阅参数
    fabu(eventName, ...args) {
        if(!this.eventMap.has(eventName)) return;
        
        //根据订阅名称得到一个数组
        const arrEvent = this.eventMap.get(eventName);
        
        //遍历数组, 直接从1开始,然后 3,5,7,9....
        for(let i=1;i{console.log("订阅者A: " + a1 + a2)});
const key2 = eb.dinyue("key2",(a1)=>{console.log("订阅者B: " +a1)});
eb.dinyue("key3",(a1)=>{console.log("订阅者C: " + a1)},true);
eb.dinyue("key3",(a1)=>{console.log("订阅者D: " + a1)},false);

//console.log((eb));
//eventMap: Map (3)
//key "key1"
//value ["0", function] (2)
//key "key2"
//value ["1", function] (2)
//key "key3"
//value ["O2", function, "3", function] (4)

eb.fabu("key1","i am key1",",haha");
eb.fabu("key2","i am key2");

eb.quxiao(key2);
eb.fabu("key2","i am key22");

eb.fabu("key3","i am key3哈哈");
eb.fabu("key3","i am key3-1哈哈");

//订阅者A: i am key1,haha
//1449970f22d6e671c3413a9b4a068271.js:328 订阅者B: i am key2
//1449970f22d6e671c3413a9b4a068271.js:328 key2-1: 已经被取消
//1449970f22d6e671c3413a9b4a068271.js:328 订阅者C: i am key3哈哈
//1449970f22d6e671c3413a9b4a068271.js:328 订阅者D: i am key3哈哈
//1449970f22d6e671c3413a9b4a068271.js:328 key3-O2: 已经被执行
//1449970f22d6e671c3413a9b4a068271.js:328 订阅者D: i am key3-1哈哈

你可能感兴趣的:(学习 Javascript 之EventBus Map版)