Write an EventBus using Map

The code for the EventBus class written in this article can be viewed in DC-utils


Front knowledge

Map documents

Design patterns

EventBus

class EventBus {
    constructor () {
      this.events = new Map()}// Listen on events
    addListener (type, cb) {
        if(! type || ! cb)return; // The event name and callback must be passed
        if (!this.events.has(type)) { // The event does not exist
            this.events.set(type, []) // Initializes an empty array to hold the callback
        }
        this.events.get(type).push(cb); // Save the callback
    }
    // Trigger the event
    dispatchListener (type, params) {
        if(! type || !this.events.has(type)) return; // The event name must be passed. There is no direct return
        let cbs = this.events.get(type); // Get the callback array
        if (cbs) {
            cbs.forEach(cb= > { // Iterate over the call callback function and pass in the arguments
                cb.call(this, params) }); }}// Cancel the event
    removeListener (type, cb) {
        if(! type || !this.events.has(type)) return; // The event name must be passed. There is no direct return
        if (cb) { // Specify the callback to delete
            let cbs = this.events.get(type);
            for (let i = 0; i < cbs.length; i++) { // Iterate through the callback array to find the target callback and delete it
                if(cbs[i] === cb) {
                    cbs.splice(i, 1);
                    break}}}else { // Clear the entire event without an explicit callback
            this.events.delete(type)
        }
    }
}
Copy the code

test

let eventBus = new EventBus();
let fun1 = function () {
    console.log(1)}let fun2 = function () {
    console.log(2)}let fun3 = function () {
    console.log(3)
}
eventBus.addListener("type1",fun1)
eventBus.addListener("type1",fun2)
eventBus.addListener("type1",fun3)

eventBus.dispatchListener("type1")

eventBus.removeListener("type1",fun2)

eventBus.dispatchListener("type1")

let fun4 = function (v) {
    console.log(v)
}

eventBus.addListener("type2",fun4)

eventBus.dispatchListener("type2"."this is a parameter")

eventBus.removeListener("type2")

eventBus.dispatchListener("type2"."this is another parameter")

console.log(eventBus)
  
Copy the code

The results of