Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
PubSub-JS is a lightweight JavaScript library for implementing the publish/subscribe pattern. It allows you to create a simple messaging system where you can publish events and subscribe to them, making it easier to manage communication between different parts of your application.
Publishing Events
This feature allows you to publish events to a specific topic. Other parts of your application can then subscribe to this topic and react to the event.
const PubSub = require('pubsub-js');
// Publish an event
PubSub.publish('MY TOPIC', { message: 'Hello World!' });
Subscribing to Events
This feature allows you to subscribe to a specific topic. When an event is published to this topic, the subscriber function will be called with the event data.
const PubSub = require('pubsub-js');
// Subscribe to an event
const mySubscriber = (msg, data) => {
console.log(`Message: ${msg}, Data: ${JSON.stringify(data)}`);
};
const token = PubSub.subscribe('MY TOPIC', mySubscriber);
Unsubscribing from Events
This feature allows you to unsubscribe from a specific topic using the token received when you subscribed. This is useful for cleaning up and preventing memory leaks.
const PubSub = require('pubsub-js');
// Unsubscribe from an event
PubSub.unsubscribe(token);
EventEmitter3 is a high-performance event emitter for Node.js and the browser. It provides a similar publish/subscribe pattern but with more advanced features like wildcard event listeners and event namespaces. It is more feature-rich compared to PubSub-JS.
Mitt is a tiny (~200 bytes) functional event emitter. It provides a simple and minimalistic API for event handling, similar to PubSub-JS, but with a smaller footprint and fewer features.
PubSubJS is a dependency free publish/subscribe library for JavaScript.
PubSubJS has synchronisation decoupling, so messages are delivered asynchronously. This helps keep your program predictable as the originator of messages will not be blocked while consumers process messages.
For the adventurous, PubSubJS also supports synchronous message publication. This can give a speedup in some environments (browsers, not all), but can also lead to some very difficult to reason about programs, when one message triggers publication of another message in the same execution chain.
For benchmarks, see A Comparison of JS Publish/Subscribe Approaches
There are several ways of getting PubSubJS
npm install pubsub-js
)bower install pubsub-js
)// create a function to receive messages
var mySubscriber = function( msg, data ){
console.log( msg, data );
};
// add the function to the list of subscribers for a particular message
// we're keeping the returned token, in order to be able to unsubscribe
// from the message later on
var token = PubSub.subscribe( 'MY MESSAGE', mySubscriber );
// publish a message asyncronously
PubSub.publish( 'MY MESSAGE', 'hello world!' );
// publish a message syncronously, which is faster in some environments,
// but will get confusing when one message triggers new messages in the
// same execution chain
// USE WITH CAUTION, HERE BE DRAGONS!!!
PubSub.publishSync( 'MY MESSAGE', 'hello world!' );
// create a function to receive the message
var mySubscriber = function( msg, data ){
console.log( msg, data );
};
// add the function to the list of subscribers to a particular message
// we're keeping the returned token, in order to be able to unsubscribe
// from the message later on
var token = PubSub.subscribe( 'MY MESSAGE', mySubscriber );
// unsubscribe from further messages
PubSub.unsubscribe( token );
// create a function to receive the message
var mySubscriber = function( msg, data ){
console.log( msg, data );
};
// add the function to the list of subscribers to a particular message
// we're keeping the returned token, in order to be able to unsubscribe
// from the message later on
var token = PubSub.subscribe( 'MY MESSAGE', mySubscriber );
// unsubscribe mySubscriber from ALL further messages
PubSub.unsubscribe( mySubscriber );
// create a subscriber to receive all messages 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 message 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
Use "constants" for topics and not string literals. PubSubJS uses strings as topics, and will happily try to deliver your messages with ANY topic. So, save yourself from frustrating debugging by letting the JavaScript engine complain when you make typos.
// 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");
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;
By default PubSubJS can be used in any browser or CommonJS environment, including node. Additionally, PubSubJS can be built specifically for jQuery.
$ rake jquery
Produces jquery.pubsub.js
var topic = 'greeting',
data = 'world'
subscriber = function sayHello( data ){
console.log( 'hello ' + data );
};
// add a subscription
var token = $.pubsub('subscribe', topic, sayHello );
// 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
There are grunt tasks for helping with linting and testing the codebase.
The tests are implemented using BusterJS and the excellent Sinon.JS. You will need to install BusterJS in order to run the tests.
$ grunt lint
If you have PhantomJS installed on your system, you can run the Buster tests by running
$ grunt test
or by running
$ npm test
PubSubJS uses Semantic Versioning for predictable versioning.
v1.3.6
v1.3.5
v1.3.4
v1.3.3
This version should from an API perspective be exactly the same as v1.3.2. Changes were only made to make PubSubJS more suitable for distribution via npm.
v1.3.2
v1.3.1
v1.3.0
v1.2.2
v1.2.0
v1.1.0
v1.0.3
MIT: http://mrgnrdrck.mit-license.org
These are a few alternative projects that also implement topic based publish subscribe in JavaScript.
FAQs
Dependency free publish/subscribe library
The npm package pubsub-js receives a total of 201,041 weekly downloads. As such, pubsub-js popularity was classified as popular.
We found that pubsub-js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.