eventBus实现,对业务开发非常有用。

437 阅读1分钟

监听/发布者模式写出的bus

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()

使用方法如下

import bus from 'bus.js'

function cb() {
    ...
}

bus.$on('eventName', cb) // 将回调绑定事件

bus.$emit('eventName', data) // 触发事件,传入参数 data,执行回调

bus.$unload('eventName', cb) // 删除 eventName 事件中绑定的回调

觉得对你有帮助,点个赞可好呀~~