0.13.0 • Public • Published

PSub Build Status Codecov branch npm Commitizen friendly

Implementation of the Publish/Subscribe design pattern using ES6 features. Think Event Emitter.

What is Publish/Subscribe?

It is an event system that allows us to define application specific events which can serve as triggers for message passing between various parts of an application. The main idea here is to avoid dependencies and promote loose coupling. Rather than single objects calling on the methods of other objects directly, they instead subscribe to a specific topic (event) and are notified when it occurs.


  • ES6 Symbols as subscription tokens (always unique)
  • Constant O(1) subscribe/unsubscribe time (How It Works)
  • Wildcard publish to all listeners using the '*' topic
  • Asynchronous publish with microtasks
  • Method names we're all used to (subscribe === on, publish === emit, unsubscribe === off)
  • No dependencies
  • Small (~800b gzipped and compressed)



// emitter that logs any publish events
import PSub from 'psub';
class PSubLogger extends PSub {
  constructor() {
  publish(evt, ...args) {
    console.log(`publish (${evt}): ${args}`);
    super.publish(evt, ...args);

Using (Node)

import http from 'http';
import PSub from 'psub';
const ps = new PSub();
// can also use ps.on
ps.subscribe('request', ({ method, url }) => {
http.createServer((req, res) => {
  // can also use ps.emit
  ps.publish('request', req);
}).listen(1337, '');

Using (Browser)

import PSub from 'psub';
const ps = new PSub();
ps.subscribe('email/inbox', ({
}) => {
  new Notification(`Sent: ${subject}`, {
  .addEventListener('click', () => {
    const form = new FormData(document.getElementById('email-form'));
    fetch('/login', {
      method: 'POST',
      body: form
    }).then((response) => {
      ps.publish('email/inbox', response);


// extract the default export
const { PSub } = require('psub');
const ps = new PSub();
// ...

Browser Script

Add the code as a script or use the unpkg cdn

<script src=""></script>
// extract the default export
const { PSub } = window.PSub;
const ps = new PSub();
// ...


  • yarn
yarn add psub
  • npm
npm i psub



Class representing a PSub object

Kind: global class

new PSub()

Create a PSub instance.

pSub.subscribe(topic, handler) ⇒ Symbol

Subscribes the given handler for the given topic.

Kind: instance method of PSub
Alias: on
Returns: Symbol - Symbol that can be used to unsubscribe this subscription

Param Type Description
topic String Topic name for which to subscribe the given handler
handler function Function to call when given topic is published


// subscribe for the topic "notifications"
// call onNotification when a message arrives
const subscription = psub.subscribe(
  'notifications', // topic name
  onNotification,  // callback

pSub.publish(topic, ...args)

Method to publish data to all subscribers for the given topic.

Kind: instance method of PSub
Alias: emit

Param Type Description
topic String cubscription topic
...args Array arguments to send to all subscribers for this topic


// publish an object to anybody listening
// to the topic 'message/channel'
psub.publish('message/channel', {
  id: 1,
  content: 'PSub is cool!'

pSub.unsubscribe(symbol) ⇒ Boolean

Cancel a subscription using the subscription symbol

Kind: instance method of PSub
Alias: off
Returns: Boolean - true if subscription was cancelled, false otherwise

Param Type Description
symbol Symbol subscription Symbol obtained when subscribing


// unsubscribe using the subscription symbol
// obtained when you subscribed
const didUnsubscribe = psub.unsubscribe(subscriptionSymbol);

How it works

The PSub class internally maintains two maps.

  1. Map<topic,subscriptionsList>
  2. Map<symbol,subscriptionLocation>
  • Subscribing

    When ps.subscribe(topic, handler) is called, PSub looks up the list of existing subscriptions from Map<topic,subscriptionsList> and appends the new subscription handler to the obtained list. Then it creates a new Symbol to represent this subscription and creates a subscription location POJO of the form { topic: subscriptionTopic, index: positionInSubscriptionsArray }, adding them to Map<symbol,subscriptionLocation>. Finally it returns the created Symbol.

  • Publishing

    When ps.publish(topic) is called, PSub looks up the list of existing subscriptions from Map<topic,subscriptionsList> and invokes their handlers, each in its own microtask, passing along any provided arguments.

  • Unsubscribing

    When ps.unsubscribe(symbol) is called, PSub uses this symbol to obtain a subscription location from Map<symbol,subscriptionLocation>. It then extracts the topic and position for this subscription from the obtained subscription location and removes the subscription from Map<topic,subscriptionsList>. Finally it does some necessary cleanup and return true to signal success.



Package Sidebar


npm i psub

Weekly Downloads






Last publish


  • nem035