eventservice
TypeScript icon, indicating that this package has built-in type declarations

1.4.3 • Public • Published

eventservice

The Promise-based simple event bus service

Build Status

Installation

npm install --save eventservice

Usage

Simple usage

import EventService from "eventservice";

// subscribe to event with name "SomeEventName"
EventService.on("SomeEventName", async () => {
    //do something
    console.log("Did something!");
});

// to trigger event.
await EventService.fire("SomeEventName", null);
// -> Did something!

Passing data to the subscriber

import EventService from "eventservice";

// subscribe to event with name "SomeEventName"
EventService.on("SomeEventName", async (date: Date) => {
    console.log(date);
});

// to trigger event. Take a look to the second arg
await EventService.fire("SomeEventName", new Date());
// -> current date

Getting date from the subscriber

Use method on.

import EventService from "eventservice";

// subscribe to event with name "SomeEventName"
EventService.on("SomeEventName", async () => {
    return "Hello World!"
});

// to trigger event.
const result: string = await EventService.fire<string>("SomeEventName", null);
console.log(result); // -> Hello World!

Waiting a nested event

import EventService from "eventservice";

// subscribe to event with name "SomeEventName2"
EventService.on("SomeEventName2", (name: string) => {
    return new Promise<string>((resolve, reject) => {
        setTimeout(() => resolve(`Hello ${name}!`, 5000));
    });
});

// subscribe to event with name "SomeEventName1"
EventService.on("SomeEventName1", async (name: string) => {
    return await EventService.fire<string>("SomeEventName1", name);
});

// to trigger event. Take a look to the latest arg
const result: string = await EventService.fire<string>("SomeEventName1", "World");
console.log(result); // after 5s -> Hello World!

Unsubscribe

You can use method off

import EventService from "eventservice";

// subscribe to event with name "SomeEventName"
EventService.on("SomeEventName", async (name: string) => {
    return `Hello ${name}!`;
}, "SomeKey");

// unsubscribe to event with name "SomeEventName"
EventService.off("SomeEventName", "SomeKey");

// to trigger event. Take a look to the latest arg
const result: string = await EventService.fire<string>("SomeEventName", "World");
console.log(result); // undefined

Credits

Alexey Ripenko, GitHub

License

MIT

/eventservice/

    Package Sidebar

    Install

    npm i eventservice

    Weekly Downloads

    3

    Version

    1.4.3

    License

    MIT

    Unpacked Size

    28.9 kB

    Total Files

    19

    Last publish

    Collaborators

    • alexeyripenko