奇技淫巧之发布订阅模式

133 阅读1分钟
  • 别的不多说,上去就是撸!

let event {
    // 事件列表
    list: [],
    
    // 订阅事件
    on(key, fn) {
        // 判断是否已有该事件类型
        if (!this.list[key]) {
            thhis.list[key] = [];
        }
        // 将订阅的事件引用保存到该类型的事件数组中
        this.list[key].push(fn);
    },
    // 发布事件
    emit() {
        // 获取参数列表中第一个参数(获取事件类型的引用)
        const args = Array.from(arguments);
        let key = args.shift();
        const fnsList = this.list[key]; // 获取该类型的所有事件
        // 该事件类型不存在,返回false
        if (!fnsList || fnsList.length === 0) {
            return false;
        }
        // 执行该类型的所有事件
        fnsList.forEach(fn => {
            fn.apply(this, args);
        });
    },
    // 取消订阅
    remove(key, fn) {
        // 找到key类型的事件列表
        const fnsArray = this.list[key];
        // 如果没有该类型事件。返回false
        if (!fnsArray) {
            return false;
        }
        // 清空key类型的所有事件
        if (!fn) { // 当不传fn时,表示清除所有key类型的事件
            fnsArray && (fns.length = 0);
        } else { // 清除指定类型的指定事件
            fnsArray.forEach((currentFn, index) => {
                if (currentFn === fn) {
                    fnsArray.splice(index, 1);
                }
            });
        }
    }
};