Handle any Javascript and Typescript function using pub/sub.
Special thanks to David Walsh (@darkwing) for the inspiration!
npm i consecute
Import the globally available instance
import cs from 'consecute'; // Globally available instance
Or instanciate your own instance
import { consecute } from 'consecute';
const cs = consecute();
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
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>`
});