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

psub

v0.13.0

Published

Publish/Subscribe (Event Emitter)

Downloads

15

Readme

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