Nocturnal Parakeet Monitor

    @a-z.ren/event-hub
    TypeScript icon, indicating that this package has built-in type declarations

    3.1.2 • Public • Published

    Event Hub

    Simple Event Hub

    Table of Contents

    Advantage

    public subscriber: Map<string, Set<EventHandler>> = new Map();

    The EventHub uses Map and Set to store EventHandler. has better performance and more concise code to implement core functions than using Object and Array.

    The disadvantage is that it only supports ES6 or above, and no longer has performance advantage after compiling to ES5.

    Install

    npm i @a-z.ren/event-hub

    Usage

    JavaScript

    import EventHub from "@a-z.ren/event-hub";

    TypeScript

    import EventHub from "@a-z.ren/event-hub/src/EventHub";

    Basic functions:

    const eventHub = new EventHub();
    
    function handlerA() {
      console.log("I'm A!");
    }
    
    eventHub.on("1", handlerA);
    eventHub.on("1", (a, b) => console.log(`I'm B, I like ${a} and ${b}!`));
    eventHub.once("1", () => console.log("I'm C, I only be triggered once!"));
    
    eventHub.emit("1", "🐱", "🐶");
    // I'm A!
    // I'm B, I like 🐱 and 🐶!
    // I'm C, I only be triggered once!
    
    eventHub.off("1", handlerA);
    eventHub.emit("1", "🍦", "🍰");
    // I'm B, I like 🍦 and 🍰!

    Promise and Async/Await:

    (async function () {
      const value = await eventHub.promise("2");
      console.log("Await " + value);
    })();
    
    eventHub
      .promise("2")
      .then((value) => "Then " + value)
      .then(console.log);
    
    eventHub.emit("2", "Hello");
    // Await Hello
    // Then Hello

    Extends

    class ChatCat extends EventHub {
      sayHello() {
        this.emit("say", "Hello!");
      }
      sayGood() {
        this.emit("say", "Good!");
      }
    }
    
    const cat = new ChatCat();
    
    cat.on("say", console.log);
    
    cat.sayHello();
    // Hello!
    
    cat.sayGood();
    // Good!

    Gather

    eventHub.on("4", (value) => "Love " + value);
    eventHub.once("4", (value) => "Good " + value);
    eventHub.gather("4", "gather").forEach((result) => console.log(result));
    // Love gather
    // Good gather

    Contribute

    1. Fork the repository
    2. Create Feat_xxx branch
    3. Commit your code
    4. Create Pull Request

    License

    MIT © A-Z.REn

    Install

    npm i @a-z.ren/event-hub

    DownloadsWeekly Downloads

    17

    Version

    3.1.2

    License

    MIT

    Unpacked Size

    12.7 kB

    Total Files

    11

    Last publish

    Collaborators

    • lzqcn