eventBus實現,對業務開發很是有用。

監聽/發佈者模式寫出的busbash

let Bus = function() {
    this.eventObj = {}
}

Bus.prototype.$on = function(event, fn) {
    if (Object.prototype.toString.call(this.eventObj[event]) === '[object Array]') {
        this.eventObj[event].push(fn)
    } else {
        this.eventObj[event] = [fn]
    }
}

Bus.prototype.$emit = function(event, data) {
    debugger
    if (this.eventObj[event] instanceof Array) {
        this.eventObj[event].forEach((fn) => {
            fn(data)
        })
    }
}

Bus.prototype.$unload = function(event, fn) {
    if (this.eventObj[event] instanceof Array) {
        this.eventObj[event].forEach((item, index) => {
            if (item === fn) {
                this.eventObj[event].splice(index, 1)
            }
        })
    }
}

export default new Bus()

複製代碼

使用方法以下ui

import bus from 'bus.js'

function cb() {
    ...
}

bus.$on('eventName', cb) // 將回調綁定事件

bus.$emit('eventName', data) // 觸發事件,傳入參數 data,執行回調

bus.$unload('eventName', cb) // 刪除 eventName 事件中綁定的回調

複製代碼

以爲對你有幫助,點個贊可好呀~~this

相關文章
相關標籤/搜索