Simple implementation of the event publish subscribe model:

Implementation idea:
  1. Declare a class EventEmitter
  2. Add a private this.db object to hold events
  3. The emit() method, which is used to publish events
  4. The on() method is used to subscribe to events
  5. The once() method, which is used to subscribe to events and perform only one event callback before destroying them
  6. The off() method is used to unsubscribe a callback for a certain type of event (events of a type usually have multiple subscriptions, so there are multiple callbacks).
Specific code implementation:
export class EventEmitter {
  constructor() {
    // Add a private property this.db object, which is used to hold the event. The key name is the event type and the key value is the event callback array
    this.db = Object.create(null)}// Publish events
  emit(type, payload) {
    // Do a cache and convert the object to an array
    const handlers = (this.db[type] || []).slice()
    // Publishing an event also triggers callbacks that subscribed to the event
    if (handlers && handlers.length) {
      handlers.forEach(handler= > handler(payload))
    }
  }
  // Subscribe to events
  on(type, handler) {
    // If this type of event is subscribed for the first time, this creates an array based on that type of event, holding the callbacks for that type of event
    if (!this.db[type]) {
      this.db[type] = []
    }
    // If an event of this type already exists, add the callback directly to the callback array of the event
    this.db[type].push(handler)
    return this
  }
  // Subscribe only once, which means the callback will only be executed once
  once(type, handler) {
    const emiter = this
    // The implementation method is very simple, in fact, override the callback, the completion of the callback to call off the destruction method
    function on() {
      emiter.off(type, on)
      handler.apply(emiter, arguments)
    }
    emiter.on(type, on)
  }
  // Unregister a callback for a certain type of event
  off(type, handler) {
    const handlers = this.db[type]
    // If this type of event has a callback
    if (handlers) {
      // Iterate through the callback array
      for (let i = 0; i < handlers.length; ++i) {
	// Find the callback to destroy and remove it from the event callback array
        if (handlers[i] === handler) {
          handlers.splice(i, 1)
          break
        }
      }
    }
  }
}
// Create an instance of EvnentEmitter
export const eventEmitter = new EventEmitter()
Copy the code