js發(fā)布訂閱模式簡單實現(xiàn)(vue中,$on, $emit, $off)

一般包含四個流程:

  • 存儲訂閱函數(shù)的對象events:{}
  • 訂閱事件的方法on(eventName, callback)
  • 觸發(fā)事件的方法emit(eventName, callback)

簡單粗暴直接上代碼:

    // 簡單的訂閱發(fā)布
    class Event {
        constructor() {
            // 存儲事件
            this.callbacks = {}
        }

        // 監(jiān)聽
        $on(name, fn) {
          // 一個名字可以訂閱多個事件函數(shù)
            (this.callbacks[name] || (this.callbacks[name] = [])).push(fn)
        }

        // 觸發(fā)
        $emit(name, arg) {
            let cbs = this.callbacks[name]
            if (cbs) {
                cbs.forEach(v => {
                    v.call(this, arg)
                })
            }
        }

        //  移除事件
        $off(name) {
            this.callbacks[name] = null
        }
    }
//   簡單使用
    let event = new Event()
    event.$on('event1', function(arg) {
        console.log('事件1', arg)
    })
    event.$on('event2', function(arg) {
        console.log('事件2', arg)
    })

    event.$emit('event1', {name: 'anyway'})
    event.$emit('event2', {age: '28'})
執(zhí)行結(jié)果
最后編輯于
?著作權(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)容