Skip to content

Handle any Javascript and Typescript function using pub/sub.

License

Notifications You must be signed in to change notification settings

mats852/consecute

Repository files navigation

consecute

Handle any Javascript and Typescript function using pub/sub.

consecute Github licence CI

Special thanks to David Walsh (@darkwing) for the inspiration!

Installation

npm i consecute 

Getting started

Import the globally available instance

import cs from 'consecute'; // Globally available instance

Or instanciate your own instance

import { consecute } from 'consecute';
const cs = consecute();

Usage

Subscribe and publish simple usage

const sub = cs.subscribe('interesting-topic', yourFunction);

cs.publish('interesting-topic', your, arguments, here)
  .then((promiseSettledResults) => maybeDoSomethingIfYouLike());

sub.remove(); // deletes this specific subscription

cs.clear(); // clear all topics

Typescript safety

You can merge the EventMapBase declaration to specify your hook types.

interface EventMapBase {
  bingo: [string, number];
}

cs.subscribe('bingo', (one, two) => {
//                     ^^^^^^^^ These have the type `string`, `number`
});

You can also extend the EventMapBase for your separate instances.

interface MyEventMap extends EventMapBase {
  binga: number;
  bingo: { a: number, b: string };
  bingu: [string, number, boolean];
}

const customInstance = consecute<MyEventMap>();

customInstance.subscribe('binga', (one) => {
//                                 ^^^ This has the type `number`
});

customInstance.subscribe('bingo', (one) => {
//                                 ^^^ This has the type `{ a: number, b: string }`
});

customInstance.subscribe('bingu', (one, two, three) => {
//                                 ^^^^^^^^^^^^^^^ These have the type `string`, `number` and `boolean` respectively
});

In the case where you would want to send an array as a standalone argument (not spread), you would do this

interface MyEventMap extends EventMapBase {
  bingy: [Array<string>];
}

const customInstance = consecute<MyEventMap>();

customInstance.subscribe('bingy', (one) => {
//                                 ^^^ This has the type `Array<string>`
});

About

Handle any Javascript and Typescript function using pub/sub.

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published