code

/** * EventBus * implements communication between objects and automatically listens for events when data or features change */
class EventBus {
  constructor(name = 'EventBus') {
    this.name = name
    // Singleton mode
    this._events = this._events || new Object(a)// Store custom events
  }
  /** * Register event *@param {String} EventName Name of the binding event *@param {Function} Callback executes the method */
  on(eventName, callback) {
    // Check whether the event exists
    if (!this._events[eventName]) {
      this._events[eventName] = [callback]
    } else {
      this._events[eventName].push(callback)
    }
  }

  /** * destroy * after binding once@param {String} EventName Name of the binding event *@param {Function} callback 
   */
  once(eventName, callback) {
    let once = (. args) = > {
      this.off(eventName) callback(... args) }this.on(eventName, once)
  }

  /** * destruction event *@param {String} EventName Specifies the name of the destruction event */
  off(eventName) {
    if (this._events[eventName]) {
      delete this._events[eventName]
      console.log(`${eventName}< = = destroyed `)}}/** * trigger event *@param {String} EventName Name of the binding event *@param  {... any} The argument passed by args is */
  emit(eventName, ... args) {
    if (this._events[eventName]) {
      this._events[eventName].forEach(callback= >{ callback([...args]); })}else {
      console.error(`${eventName}The <== bind event does not exist or has been destroyed)}}}let emiter = new EventBus()

emiter.on('test'.args= > {
  console.log(args);
})
emiter.on('test'.args= > {
  console.log(args.join());
})
emiter.on('test1'.args= > {
  console.log(args.join());
})

// Trigger the event
emiter.emit('test'.11.11.11)
emiter.off('test')
emiter.emit('test'.11.12.31)
Copy the code

Matters needing attention

Usage scenarios