Bus written in listener/publisher mode

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

Copy the code

The usage is as follows

import bus from 'bus.js'

function cb() {... } bus.$on('eventName'Cb) // Bind the callback to the event bus.$emit('eventName', data) // Trigger the event, pass in the parameter data, perform the callback bus.$unload('eventName'Cb) // Delete the callback bound to eventNameCopy the code

Think it’s helpful to you, please give it a thumbs-up