A global publish-subscribe event mechanism to facilitate direct communication between components with ambiguous hierarchical relationships.

Code

  • EventBox.js
// Simply implement a publish-subscribe event pool class

export default class EventBox {
    handlers = {}

    emit = (event, ... payload) = > {
      const handlers = this.handlers[event];
      if(! handlers || ! handlers.length) {return;
      }

      const count = handlers.length;

      for (let i = 0; i < count; i++) {
        const handler = handlers[i];
        if (typeof handler === 'function') { handler(... payload); } } } on =(event, handler) = > {
      if (!this.handlers[event]) {
        this.handlers[event] = [];
      }

      this.handlers[event].push(handler);

      const off = () = > {
        this.off(event, handler);
      };

      return {
        off,
        remove: off,
      };
    }

    off = (event, handler) = > {
      const handlers = this.handlers[event];
      if(! handlers || ! handlers.length) {return;
      }

      for (let i = handlers.length; i-- > 0;) {
        if (handler === handlers[i]) {
          console.log(`remove ${event}`);
          handlers.splice(i, 1); }}}}Copy the code
  • index.js
import EventBox from './EventBox'

const globalEvents = new EventBox()

export const on = globalEvents.on
export const off = globalEvents.off
export const emit = globalEvents.emit

export default globalEvents
Copy the code

Usage

 import eventBox from './event-box';

 // bindEvent
 let menuDidUpdateHandler = eventBox.on('didUpdateEvent'.() = > {
    adaptDocHeight(); // some funs
  });

 // removeEvent
 if (menuDidUpdateHandler) {
    menuDidUpdateHandler.off();
 }
Copy the code