javascript 實現(xiàn)訂閱發(fā)布模式

class EventEmitter {
    constructor() {
        // 定義存放事件訂閱的存儲變量
        this.listeners = {};
    }

    on(type, cb) {
        let cbs = this.listeners[type];
        if (!cbs) {  // 判斷是否已經(jīng)有訂閱
            cbs = [];
        }
        // 訂閱一則事件
        cbs.push(cb);
        this.listeners[type] = cbs;
        return this;
    }

    emit(type, ...args) {
        const cbs = this.listeners[type];
        if (Array.isArray(cbs)) {
            for (let i = 0; i < cbs.length; i++) {
                const cb = cbs[i];
                if (typeof cb === 'function') {
                    // 觸發(fā)一則事件
                    cb(...args);
                }
            }
        }
        return this;
    }

    off(type, cb) {
        if (cb) {  // 如果有回調(diào),則取消訂閱該回調(diào)
            let cbs = this.listeners[type];
            cbs = cbs.filter(eMap => eMap.cb !== cb);
            this.listeners[type] = cbs;
        } else {  // 否則取消訂閱整個事件
            this.listeners[type] = null;
            delete this.listeners[type];
        }
        return this;
    }
}

export default new EventEmitter();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容