psub

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.

Features

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

Example

Extending

// emitter that logs any publish events
import PSub from 'psub';
 
class PSubLogger extends PSub {
  constructor() {
    super();
  }
 
  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 }) => {
  console.log(`${method}${url}`);
});
 
http.createServer((req, res) => {
  // can also use ps.emit
  ps.publish('request', req);
  res.end('Works!');
}).listen(1337, '127.0.0.1');

Using (Browser)

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

CommonJS

// 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="https://unpkg.com/psub@latest/dist/index.umd.js"></script>
// extract the default export
const { PSub } = window.PSub;
 
const ps = new PSub();
// ...

Installation

  • yarn
yarn add psub
  • npm
npm i psub

API

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

Example

// 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

Example

// 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

Example

// 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.

Licence

MIT

Package Sidebar

Install

npm i psub

Weekly Downloads

4

Version

0.13.0

License

MIT

Last publish

Collaborators

  • nem035