PHPackages                             mroderick/pubsubjs - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mroderick/pubsubjs

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mroderick/pubsubjs
==================

Dependency free publish/subscribe for JavaScript

08.9kJavaScript

Since Jun 12Pushed 11y ago10 watchersCompare

[ Source](https://github.com/Sparhandy/PubSubJS)[ Packagist](https://packagist.org/packages/mroderick/pubsubjs)[ RSS](/packages/mroderick-pubsubjs/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependenciesVersions (1)Used By (0)

PubSubJS
========

[](#pubsubjs)

[![Build Status](https://camo.githubusercontent.com/aa2cbdd7d2cd9acd6a82177fc2f0d5e58006390211fa22ecaa141e3dbfd16229/68747470733a2f2f7472617669732d63692e6f72672f6d726f64657269636b2f5075625375624a532e706e67)](https://travis-ci.org/mroderick/PubSubJS) [![NPM version](https://camo.githubusercontent.com/64a48a06de408f19fa230876382c232aec1fe35829b7ae72e71a3644a1e832f4/68747470733a2f2f62616467652e667572792e696f2f6a732f7075627375622d6a732e706e67)](http://badge.fury.io/js/pubsub-js)

PubSubJS is a [topic-based](http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern#Message_filtering) [publish/subscribe](http://en.wikipedia.org/wiki/Publish/subscribe) library written in JavaScript.

PubSubJS has synchronisation decoupling, so topics are published asynchronously. This helps keep your program predictable as the originator of topics will not be blocked while consumers process them.

For the adventurous, PubSubJS also supports synchronous topic publication. This can give a speedup in some environments (browsers, not all), but can also lead to some very difficult to reason about programs, where one topic triggers publication of another topic in the same execution chain.

For benchmarks, see [A Comparison of JS Publish/Subscribe Approaches](http://jsperf.com/pubsubjs-vs-jquery-custom-events/51)

#### Single process

[](#single-process)

PubSubJS is designed to be used within a **single process**, and is not a good candidate for multi-process applications (like [Node.js – Cluster](http://nodejs.org/api/cluster.html) with many sub-processes). If your Node.js app is a single process app, you're good. If it is (or is going to be) a multi-process app, you're probably better off using [redis Pub/Sub](http://redis.io/topics/pubsub) or similar

Key features
------------

[](#key-features)

- Dependency free
- Synchronization decoupling
- ES3 compatible. PubSubJS should be able to run everywhere that can execute JavaScript. Browsers, servers, ebook readers, old phones, game consoles.
- AMD / CommonJS module support
- No modification of subscribers (jQuery custom events modify subscribers)
- Easy to understand and use (thanks to synchronization decoupling)
- Small(ish), less than 1kb minified and gzipped

Getting PubSubJS
----------------

[](#getting-pubsubjs)

There are several ways of getting PubSubJS

- [Download a tagged version](https://github.com/mroderick/PubSubJS/tags) from GitHub
- Install via npm (`npm install pubsub-js`)
- Intall via bower (`bower install pubsub-js`)

Examples
--------

[](#examples)

### Basic example

[](#basic-example)

```
// create a function to subscribe to topics
var mySubscriber = function( msg, data ){
    console.log( msg, data );
};

// add the function to the list of subscribers for a particular topic
// we're keeping the returned token, in order to be able to unsubscribe
// from the topic later on
var token = PubSub.subscribe( 'MY TOPIC', mySubscriber );

// publish a topic asyncronously
PubSub.publish( 'MY TOPIC', 'hello world!' );

// publish a topic syncronously, which is faster in some environments,
// but will get confusing when one topic triggers new topics in the
// same execution chain
// USE WITH CAUTION, HERE BE DRAGONS!!!
PubSub.publishSync( 'MY TOPIC', 'hello world!' );
```

### Cancel specific subscripiton

[](#cancel-specific-subscripiton)

```
// create a function to receive the topic
var mySubscriber = function( msg, data ){
    console.log( msg, data );
};

// add the function to the list of subscribers to a particular topic
// we're keeping the returned token, in order to be able to unsubscribe
// from the topic later on
var token = PubSub.subscribe( 'MY TOPIC', mySubscriber );

// unsubscribe this subscriber from this topic
PubSub.unsubscribe( token );
```

### Cancel all subscriptions for a function

[](#cancel-all-subscriptions-for-a-function)

```
// create a function to receive the topic
var mySubscriber = function( msg, data ){
    console.log( msg, data );
};

// add the function to the list of subscribers to a particular topic
// we're keeping the returned token, in order to be able to unsubscribe
// from the topic later on
var token = PubSub.subscribe( 'MY TOPIC', mySubscriber );

// unsubscribe mySubscriber from ALL topics
PubSub.unsubscribe( mySubscriber );
```

### Hierarchical addressing

[](#hierarchical-addressing)

```
// create a subscriber to receive all topics from a hierarchy of topics
var myToplevelSubscriber = function( msg, data ){
    console.log( 'top level: ', msg, data );
}

// subscribe to all topics in the 'car' hierarchy
PubSub.subscribe( 'car', myToplevelSubscriber );

// create a subscriber to receive only leaf topic from hierarchy op topics
var mySpecificSubscriber = function( msg, data ){
    console.log('specific: ', msg, data );
}

// subscribe only to 'car.drive' topics
PubSub.subscribe( 'car.drive', mySpecificSubscriber );

// Publish some topics
PubSub.publish( 'car.purchase', { name : 'my new car' } );
PubSub.publish( 'car.drive', { speed : '14' } );
PubSub.publish( 'car.sell', { newOwner : 'someone else' } );

// In this scenario, myToplevelSubscriber will be called for all
// topics, three times in total
// But, mySpecificSubscriber will only be called once, as it only
// subscribes to the 'car.drive' topic
```

Tips
----

[](#tips)

Use "constants" for topics and not string literals. PubSubJS uses strings as topics, and will happily try to deliver your topics with ANY topic. So, save yourself from frustrating debugging by letting the JavaScript engine complain when you make typos.

### Example of use of "constants"

[](#example-of-use-of-constants)

```
// BAD
PubSub.subscribe("hello", function( msg, data ){
	console.log( data )
});

PubSub.publish("helo", "world");

// BETTER
var MY_TOPIC = "hello";
PubSub.subscribe(MY_TOPIC, function( msg, data ){
	console.log( data )
});

PubSub.publish(MY_TOPIC, "world");
```

### Immediate Exceptions for stack traces in developer tools

[](#immediate-exceptions-for-stack-traces-in-developer-tools)

As of versions 1.3.2, you can force immediate exceptions (instead of delayed execeptions), which has the benefit of maintaining the stack trace when viewed in dev tools.

This should be considered a development only option, as PubSubJS was designed to try to deliver your topics to all subscribers, even when some fail.

Setting immediate exceptions in development is easy, just tell PubSubJS about it after it's been loaded.

```
PubSub.immediateExceptions = true;
```

Plugin for jQuery
-----------------

[](#plugin-for-jquery)

By default PubSubJS can be used in any browser or CommonJS environment, including [node](http://nodejs.org). Additionally, PubSubJS can be built specifically for jQuery.

```
$ rake jquery

```

Produces jquery.pubsub.js

### Use with jQuery

[](#use-with-jquery)

```
var topic = 'greeting',
    data = 'world'
    subscriber = function sayHello( data ){
        console.log( 'hello ' + data );
    };

// add a subscription
var token = $.pubsub('subscribe', topic, subscriber );

// unsubscribing
$.pubsub('unsubscribe', token)          // remove a specific subscription
$.pubsub('unsubscribe', subscriber);    // remove all subscriptions for subscriber

// publishing a topic
$.pubsub('publish', topic, data);

// publishing topic syncronously
$.pubsub('publishSync', topic, data);
```

In the jQuery build, the global `PubSub` global is still available, so you can mix and match both `Pubsub` and `$.pubsub` as needed.

There is also an article about [Using PubSubJS with jQuery](http://roderick.dk/resources/using-pubsubjs-with-jquery/)

Contributing to PubSubJS
------------------------

[](#contributing-to-pubsubjs)

Please see [CONTRIBUTING.md](CONTRIBUTING.md)

Future of PubSubJS
------------------

[](#future-of-pubsubjs)

- Better and more extensive usage examples

More about Publish/Subscribe
----------------------------

[](#more-about-publishsubscribe)

- [The Many Faces of Publish/Subscribe](http://www.cs.ru.nl/~pieter/oss/manyfaces.pdf) (PDF)
- [Addy Osmani's mini book on Patterns](http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript)
- [Publish / Subscribe Systems, A summary of 'The Many Faces of Publish / Subscribe'](http://downloads.ohohlfeld.com/talks/hohlfeld_schroeder-publish_subscribe_systems-dsmware_eurecom2007.pdf)

Versioning
----------

[](#versioning)

PubSubJS uses [Semantic Versioning](http://semver.org/) for predictable versioning.

Changelog
---------

[](#changelog)

Please see

License
-------

[](#license)

MIT:

Alternatives
------------

[](#alternatives)

These are a few alternative projects that also implement topic based publish subscribe in JavaScript.

-
-
-  — oriented towards 'channels', free of dependencies
-  - supports vanilla, underscore, jQuery and is even available in NuGet

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/6746416?v=4)[Andy](/maintainers/An-Bo)[@An-Bo](https://github.com/An-Bo)

---

Top Contributors

[![mroderick](https://avatars.githubusercontent.com/u/20321?v=4)](https://github.com/mroderick "mroderick (139 commits)")[![krasu](https://avatars.githubusercontent.com/u/175968?v=4)](https://github.com/krasu "krasu (2 commits)")[![fernandogmar](https://avatars.githubusercontent.com/u/836876?v=4)](https://github.com/fernandogmar "fernandogmar (1 commits)")[![An-Bo](https://avatars.githubusercontent.com/u/6746416?v=4)](https://github.com/An-Bo "An-Bo (1 commits)")[![michsch](https://avatars.githubusercontent.com/u/357387?v=4)](https://github.com/michsch "michsch (1 commits)")[![joscha](https://avatars.githubusercontent.com/u/188038?v=4)](https://github.com/joscha "joscha (1 commits)")[![contolini](https://avatars.githubusercontent.com/u/1060248?v=4)](https://github.com/contolini "contolini (1 commits)")

### Embed Badge

![Health badge](/badges/mroderick-pubsubjs/health.svg)

```
[![Health](https://phpackages.com/badges/mroderick-pubsubjs/health.svg)](https://phpackages.com/packages/mroderick-pubsubjs)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
