A tiny <1KB pub-sub-based event library that lets you send custom message within and cross the window! It's written in ES6 and makes use of the awesome Broadcast Channel API.
Demo: pub-sub.lekschas.de
npm -i -D pub-sub-es
import createPubSub from 'pub-sub-es';
// Creates a new pub-sub event listener stack.
const pubSub = createPubSub();
// Subscribe to an event
const myEmojiEventHandler = (msg) => console.log(`π ${msg} π`);
pubSub.subscribe('my-emoji-event', myEmojiEventHandler);
// Publish an event
pubSub.publish('my-emoji-event', 'Yuuhuu'); // >> π Yuuhuu π
// Unsubscribe
pubSub.unsubscribe('my-emoji-event', myEmojiEventHandler);By default, pub-sub assumes you are publishing any kind of events with an
unknown payload. With TypeScript you can specify which events (name and payload)
you are publishing as follows.
import createPubSub, { Event } from 'pub-sub-es';
type Events = Event<'init' | 'destroy', undefined> &
Event<'solution', number> &
Event<'selection', number[]>;
const pubSub = createPubSub<Events>();With this, we established that pubSub will handle four events:
initanddestroyfeature no payload (i.e., the payload isundefined)solutionfeatures a singlenumberas payloadselectionfeatures an array of numbers as payload
When you listen to or publish an event, the payload will now be typed based of the event. I.e.:
pubSub.subscribe('destroy', (payload) => payload === undefined); // => β
pubSub.subscribe('destroy', (payload) => payload * 2); // => β
pubSub.subscribe('solution', (payload) => console.log(payload + 2)); // => β
pubSub.subscribe('solution', (payload) => console.log(payload.length)); // => β
pubSub.subscribe('selection', (payload) => console.log(payload.length)); // => β
pubSub.subscribe('selection', (payload) => console.log(payload * 2)); // => β
pubSub.publish('init'); // => β
pubSub.publish('init', 'w00t'); // => β
pubSub.publish('solution', 42); // => β
pubSub.publish('solution', '42'); // => β
pubSub.publish('selection', [1,3,3,7]); // => β
pubSub.publish('selection', 1337); // => βpub-sub-es exports the factory function (createPubSub) for creating a new pub-sub service by default and a global pub-sub service (globalPubSub). The API is the same for both.
Creates a new pub-sub instances
Arguments:
optionsis an object for customizing pubSub. The following properties are understood:async: whentrue, events are published asynchronously to decouple the process of the originator and consumer.caseInsensitive: whentrue, event names are case insensitivestack: is an object holding the event listeners and defaults to a new stack when being omitted.
Returns: a new pub-sub service
Publishes or broadcasts an event with some news or payload
Arguments:
eventis the name of the event to be published.newsis an arbitrary value that is being broadcasted.optionsis an object for customizing the behavior. The following properties are understood:async: overrides the globalasyncflag for a single call.isNoGlobalBroadcast: overrides the globalisGlobalflag for a single call.
Subscribes a handler to a specific event
eventis the name of the event to be published.handleris the handler function that is being called together with the broadcasted value.timesis the number of times the handler is invoked before it's automatically unsubscribed.
Returns: an object of form { event, handler }. This object can be used to automatically unsubscribe, e.g., pubSub.unsubscribe(pubSub.subscribe('my-event', myHandler)).
Unsubscribes a handler from listening to an event
eventOrSubscriptionis the name of the event to be published. Optionally,unsubscribeaccepts an object of form{ event, handler}coming fromsubscribe.handleris the event handler function to be unsubscribed from the event
Removes all currently active event listeners and unsets the event times.
Note: this endpoint is not available on the global pub-sub because it could have undesired side effects. You need to unsubscribe global event listeners manually instead.
The global pub-sub instance is created when pub-sub-es.js is loaded and provides a way for
global messaging within and between contexts. It utilizes the Broadcast Channel API. Note, when sending sending objects from one context to another you have to make sure that they are cloneable. For example, trying to broadcast a reference to a DOM element will fail.
You might have come across the awesome PubSubJS library and wonder which one to choose. First of all, both are tiny, have no dependencies, and offer async event broadcasting. The two main features that PubSubES offers are:
-
Auto-unsubscribable event listening: via
pubSub.subscribe(eventName, eventHandler, times)you can make theeventHandlerunsubscribed fromeventNameautomatically aftereventNamewas broadcastedtimestimes. -
Between-context messaging: PubSubES supports the new Broadcast Channel API so you can send events between different browser contexts, e.g., tabs.