Skip to content

Yfill/event-hub

Repository files navigation

GitHub license Code Style NPM Package Monthly Downloads Build Size Dependencies Status DevDependencies Status

An event hub.

Install

using npm:

npm install @yfill/event-hub --save

or using yarn:

yarn add @yfill/event-hub

Usage

  • Import resources.

    import EventHub from "@yfill/event-hub";
    <script src="https://unpkg.com/@yfill/event-hub"></script>
  • Create an EventHub instance, and then use it to monitor, broadcast, cancel monitor, and destroy.

    const eh = new EventHub();
    
    const typeHandler0 = (...arg) => {
      console.log("typeHandler0", ...arg);
    };
    const typeHandler1 = (...arg) => {
      console.log("typeHandler1", ...arg);
    };
    const typeHandler2 = (...arg) => {
      console.log("typeHandler2", ...arg);
    };
    const typeHandler3 = (...arg) => {
      console.log("typeHandler3", ...arg);
    };
    
    eh.on("$type", typeHandler0)
      .on("$type", typeHandler1)
      .on("$type", typeHandler2)
      .once("$typeOnce", typeHandler3);
    
    console.log("===First broadcast===");
    eh.emit("$type", "First broadcast", "data")
      .emit("$typeOnce", "First broadcast", "data");
    
    eh.off("$type");
    
    console.log("===Second broadcast===");
    eh.emit("$type", "Second broadcast", "data")
      .emit("$typeOnce", "Second broadcast", "data");
    
    eh.on("$type", typeHandler1)
      .on("$type", typeHandler2);
    
    console.log("===Third broadcast===");
    eh.emit("$type", "Third broadcast", "data0", "data1");
    
    eh.off("$type", typeHandler1);
    
    console.log("===Fourth broadcast===");
    eh.emit("$type", "Fourth broadcast", "data0", "data1", "data2");
    
    eh.destroy();