npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pub-sub-es

v3.0.0

Published

A simple pub-sub service

Downloads

3,774

Readme

PubSubES: A tiny ES6-based pub-sub library

npm version stability experimental build status gzipped size code style prettier demo

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

Install

npm -i -D pub-sub-es

Get Started

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);

Type Events

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:

  • init and destroy feature no payload (i.e., the payload is undefined)
  • solution features a single number as payload
  • selection features an array of numbers as payload

When you listen to an event, the payload will now be typed. I.e.:

pubSub.subscribe('solution', (payload) => console.log(payload + 2));

pubSub.publish('solution', 42); // => ✅
pubSub.publish('solution', '42'); // => ❌

API

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.

createPubSub(options = { async: false, caseInsensitive: false, stack: { __times__: {} })

Creates a new pub-sub instances

Arguments:

  • options is an object for customizing pubSub. The following properties are understood:
    • async: when true, events are published asynchronously to decouple the process of the originator and consumer.
    • caseInsensitive: when true, event names are case insensitive
    • stack: is an object holding the event listeners and defaults to a new stack when being omitted.

Returns: a new pub-sub service

pubSub.publish(event, news, options = { async: false, isNoGlobalBroadcast: false})

Publishes or broadcasts an event with some news or payload

Arguments:

  • event is the name of the event to be published.
  • news is an arbitrary value that is being broadcasted.
  • options is an object for customizing the behavior. The following properties are understood:
    • async: overrides the global async flag for a single call.
    • isNoGlobalBroadcast: overrides the global isGlobal flag for a single call.

pubSub.subscribe(event, handler, times)

Subscribes a handler to a specific event

  • event is the name of the event to be published.
  • handler is the handler function that is being called together with the broadcasted value.
  • times is 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)).

pubSub.unsubscribe(event)

Unsubscribes a handler from listening to an event

  • event is the name of the event to be published. Optionally, unsubscribe accepts an object of form { event, handler} coming from subscribe.

pubSub.clear()

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.

Between-context messaging

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, which is currently not available in all browsers. If you need to support more browsers you have to load a polyfill. PubSubES is not taking care of that! Also, when sending sending objects from one context to another you have to make sure that they are clonable. For example, trying to broadcast a reference to a DOM element will fail.

Difference to other pub-sub llibraries

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:

  1. Auto-unsubscribable event listening: via pubSub.subscribe(eventName, eventHandler, t) you can make the eventHandler unsubscribed from eventName automatically after eventName was broadcasted t times.

  2. Between-context messaging: PubSubES supports the new Broadcast Channel API so you can send events between different browser contexts, e.g., tabs.