A simple implementation of the Observer pattern with type safety! It's also dependency free and very light. The largest option in the distribution is the UMD package at 228 Bytes after brotli, and the smallest is the modern ESM package at jaw dropping 153 Bytes after brotli.
npm i dead-simple-pubsub
pnpm add dead-simple-pubsub
yarn add dead-simple-pubsub
For Web and Deno, no install is required! Just put this line at the top of your file:
import { PubSub } from 'https://cdn.skypack.dev/dead-simple-pubsub';
If you want type support with skypack, follow the directions here
<script src="https://unpkg.com/dead-simple-pubsub"></script>
And use it like you would any other package from UNPKG
Here's the great part. Unsurprisingly, the dead simple pubsub is really easy to use! Thanks to microbundle, this package supports CJS, UMD, and ESM formats. That means that wherever and however you use this package — in browser or node, with import or require — you should be set, no configuration required.
import { PubSub } from 'dead-simple-pubsub';
/** The pubsub must know the type of event it
* will be used for when it is instantiated
* ex. number or 'add'|'delete' */
const pubsub = new PubSub<number>();
/** This function takes a number and logs it to the console
* @param {number} input the number to log to the console
*/
const namedLog = (input: number): void => {
console.log(`named log: ${input}`);
};
// Add a named function to subscribers
pubsub.subscribe(namedLog);
// Publish with valid parameter
pubsub.publish(0);
/** Subscribing an anonymous function to the pubsub.
* Subscribe returns a function that unsubscribes the input
* so anonymous functions can be unsubscribed. */
const unsub = pubsub.subscribe((input: number) => {
console.log(`anonymous log: ${input}`);
});
pubsub.publish(3);
// Unsubscribing a named function
pubsub.unsubscribe(namedLog);
pubsub.publish(5);
// Unsubscribing the anonymous function
unsub();
pubsub.publish(7);
/* result */
named log: 0
named log: 3
anonymous log: 3
anonymous log: 5
If this tool isn't working for you, try one of these:
Distributed under the MIT License. See LICENSE
for more information.
Find me @illumincrotty on github or @illumincrotty on twitter