NPM Star
Collections
  1. Home
  2. Compare
  3. eventemitter3 vs pubsub-js
NPM Compare

Compare NPM packages statistics, trends, and features

CollectionsVS Code extensionChrome extensionTermsPrivacyLinkTreeIndiehackersBig Frontendqiuyumi

Event Handling Libraries: EventEmitter3 vs PubSub-js

These packages help different parts of your code communicate with each other using events. EventEmitter3 is a fast, simple way to handle events within your application, similar to Node.js's built-in EventEmitter. PubSub-js is more focused on the publish/subscribe pattern, where parts of your code can subscribe to topics and receive messages, making it great for loosely coupled applications.

Event Managementeventspub/submessagingcommunication

Detailed Comparison

Technical Analysis

featureComparison

Both packages provide event-driven communication, but eventemitter3 is more lightweight and flexible, while pubsub-js offers more advanced features like topic-based messaging and async support.

typescriptSupport

Both packages have TypeScript definitions, but eventemitter3 has better support for TypeScript 4.x.

browserCompatibility

Both packages are compatible with modern browsers, but eventemitter3 has better support for older browsers like IE11.

dependencies

eventemitter3 has no dependencies, while pubsub-js depends on the 'inherits' package.

performance

eventemitter3 is generally faster and more efficient due to its smaller size and simpler implementation.

Ecosystem Analysis

frameworkCompatibility

Both packages are compatible with popular frameworks like React, Angular, and Vue.js.

communityActivity

eventemitter3 has a more active community with more contributors and issues resolved.

documentationQuality

Both packages have good documentation, but eventemitter3's documentation is more comprehensive and up-to-date.

maintenanceStatus

eventemitter3 is more frequently updated and maintained.

Performance Comparison

bundleSizeAnalysis

eventemitter3 is significantly smaller in size, making it a better choice for production environments.

runtimePerformance

eventemitter3 is generally faster in terms of event emission and handling.

loadingTime

eventemitter3 loads faster due to its smaller size.

memoryUsage

eventemitter3 uses less memory due to its simpler implementation.

Code Examples

Basic Event Emission with eventemitter3

1const EventEmitter = require('eventemitter3');
2const emitter = new EventEmitter();
3emitter.on('event', () => {
4  console.log('Event emitted!');
5});
6emitter.emit('event');

This example shows how to create an event emitter instance, listen for an event, and emit the event using eventemitter3.

Publish-Subscribe Pattern with pubsub-js

1const PubSub = require('pubsub-js');
2const token = PubSub.subscribe('MY_TOPIC', (msg) => {
3  console.log(msg);
4});
5PubSub.publish('MY_TOPIC', 'Hello, world!');

This example shows how to subscribe to a topic and publish a message using pubsub-js.

Recommendation

Summary

eventemitter3 is a better choice for most use cases due to its smaller size, better performance, and more active community.

Details

  • Lightweight and flexible implementation
  • Better TypeScript support
  • Faster and more efficient performance

Similar Packages

mitt

90%

A tiny event emitter library that's super simple to use. It's less than 200 bytes in size and has a very straightforward API for handling events in your JavaScript applications.

Perfect for developers who want a simpler, more lightweight alternative to eventemitter3. It does the same core job but with less code and fewer features, which makes it easier to learn and use.

Event Emitter

tiny-emitter

90%

A small but capable event emitter that works in both browser and Node.js environments. Offers the basic features you need for event handling without any extra complexity.

Works as a drop-in replacement for eventemitter3 in most cases, while being smaller and simpler. Good for developers who want something easy to understand but still reliable.

Event Emitter

postal.js

90%

A powerful message bus library that helps manage communication between different parts of your application. It's like a more advanced version of pubsub-js with extra features.

Great alternative to pubsub-js when you need more advanced features like message channels and hierarchical topics. It's especially good for larger applications.

Pub/Sub Library

nanoevents

80%

A very small event emitter library focused on being as tiny as possible. It provides basic event handling capabilities with minimal overhead.

Great choice when you need the smallest possible event emitter that still works well. It's perfect for small projects or when bundle size is super important.

Event Emitter

rxjs

70%

A comprehensive library for handling events and data streams. While it's bigger than pubsub-js, it offers many powerful tools for managing how data flows through your application.

Perfect when you need more than just basic pub/sub functionality. It's great for complex applications where you need to transform, combine, or filter events in advanced ways.

Reactive Programming Library

EventEmitter3

Version npmCICoverage Status

Sauce Test Status

EventEmitter3 is a high performance EventEmitter. It has been micro-optimized for various of code paths making this, one of, if not the fastest EventEmitter available for Node.js and browsers. The module is API compatible with the EventEmitter that ships by default with Node.js but there are some slight differences:

  • Domain support has been removed.
  • We do not throw an error when you emit an error event and nobody is listening.
  • The newListener and removeListener events have been removed as they are useful only in some uncommon use-cases.
  • The setMaxListeners, getMaxListeners, prependListener and prependOnceListener methods are not available.
  • Support for custom context for events so there is no need to use fn.bind.
  • The removeListener method removes all matching listeners, not only the first.

It's a drop in replacement for existing EventEmitters, but just faster. Free performance, who wouldn't want that? The EventEmitter is written in EcmaScript 3 so it will work in the oldest browsers and node versions that you need to support.

Installation

$ npm install --save eventemitter3

CDN

Recommended CDN:

https://unpkg.com/eventemitter3@latest/dist/eventemitter3.umd.min.js

Usage

After installation the only thing you need to do is require the module:

var EventEmitter = require('eventemitter3');

And you're ready to create your own EventEmitter instances. For the API documentation, please follow the official Node.js documentation:

http://nodejs.org/api/events.html

Contextual emits

We've upgraded the API of the EventEmitter.on, EventEmitter.once and EventEmitter.removeListener to accept an extra argument which is the context or this value that should be set for the emitted events. This means you no longer have the overhead of an event that required fn.bind in order to get a custom this value.

var EE = new EventEmitter() , context = { foo: 'bar' }; function emitted() { console.log(this === context); // true } EE.once('event-name', emitted, context); EE.on('another-event', emitted, context); EE.removeListener('another-event', emitted, context);

Tests and benchmarks

This module is well tested. You can run:

  • npm test to run the tests under Node.js.
  • npm run test-browser to run the tests in real browsers via Sauce Labs.

We also have a set of benchmarks to compare EventEmitter3 with some available alternatives. To run the benchmarks run npm run benchmark.

Tests and benchmarks are not included in the npm package. If you want to play with them you have to clone the GitHub repository. Note that you will have to run an additional npm i in the benchmarks folder before npm run benchmark.

License

MIT

<div align="center"> <p> <img src="https://raw.githubusercontent.com/mroderick/PubSubJS/master/branding/logo.png"/ alt="PubSubJS" title="PubSubJS" width="200" height="200"> </p> <p> <a href="https://www.npmjs.com/package/pubsub-js"><img src="https://img.shields.io/npm/v/pubsub-js.svg?style=flat-square" alt="NPM version" title="Click to go to NPM" /></a><!-- --><a href="https://github.com/mroderick/PubSubJS/blob/master/LICENSE.md"><img src="https://img.shields.io/npm/l/pubsub-js.svg?style=flat-square" alt="MIT License" title="License" /></a><!-- --><a href="https://www.npmjs.com/package/pubsub-js"><img src="https://img.shields.io/npm/dm/pubsub-js.svg?style=flat-square" alt="NPM downloads/month" title="Click to go to NPM" /></a><!-- --><a href="https://coveralls.io/github/mroderick/PubSubJS"><img src="https://img.shields.io/coveralls/github/mroderick/PubSubJS.svg?style=flat-square" alt="Coverage Status" title="View Coverage"/></a> </p> </div>

PubSubJS is a topic-based 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.

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 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 or similar

Key features

  • Dependency free
  • synchronisation 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 synchronisation decoupling)
  • Small(ish), less than 1kb minified and gzipped

Getting PubSubJS

There are several ways of getting PubSubJS

  • Install via npm (npm install pubsub-js)
  • Use it directly from a CDN
    • https://www.jsdelivr.com/package/npm/pubsub-js
    • https://cdnjs.com/libraries/pubsub-js
    • https://unpkg.com/pubsub-js
  • Download a tagged version from GitHub

Note: the last version of this library available via bower is v1.5.4

Examples

First you have to import the module:

import PubSub from 'pubsub-js' // or when using CommonJS const PubSub = require('pubsub-js');

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 asynchronously PubSub.publish('MY TOPIC', 'hello world!'); // publish a topic synchronously, 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 subscription

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

// create a function to receive the topic var mySubscriber = function(msg, data) { console.log(msg, data); }; // unsubscribe mySubscriber from ALL topics PubSub.unsubscribe(mySubscriber);

Clear all subscriptions for a topic

PubSub.subscribe('a', myFunc1); PubSub.subscribe('a.b', myFunc2); PubSub.subscribe('a.b.c', myFunc3); PubSub.unsubscribe('a.b'); // no further notifications for 'a.b' and 'a.b.c' topics // notifications for 'a' will still get published

Clear all subscriptions

PubSub.clearAllSubscriptions(); // all subscriptions are removed

Get Subscriptions

PubSub.getSubscriptions('token'); // subscriptions by token from all topics

Count Subscriptions

PubSub.countSubscriptions('token'); // count by token from all topics

Error Handling

// isPublished is a boolean that represents if any subscribers was registered for this topic var isPublished = PubSub.publish('a'); // token will be false if something went wrong and subscriber was not registered var token = PubSub.subscribe('MY TOPIC', mySubscriber);

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

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"

// πŸ‘Ž Bad usage PubSub.subscribe('hello', function (msg, data) { console.log(data) }); PubSub.publish('hello', 'world'); // πŸ‘ Better usage var MY_TOPIC = 'hello'; PubSub.subscribe(MY_TOPIC, function (msg, data) { console.log(data) }); PubSub.publish(MY_TOPIC, 'world');

Example of use of "symbol constants" with ES6/7 syntax

// event-types.js export const MY_TOPIC = Symbol('MY_TOPIC') // somefile.js import { MY_TOPIC } from './event-types.js' PubSub.subscribe(MY_TOPIC, function (msg, data) { console.log(data) }); PubSub.publish(MY_TOPIC, 'world');

Immediate Exceptions for stack traces in developer tools

As of version 1.3.2, you can force immediate exceptions (instead of delayed exceptions), 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 has been loaded.

PubSub.immediateExceptions = true;

Contributing to PubSubJS

Please see CONTRIBUTING.md

More about Publish/Subscribe

  • The Many Faces of Publish/Subscribe (PDF)
  • Addy Osmani's mini book on Patterns
  • Publish / Subscribe Systems, A summary of 'The Many Faces of Publish / Subscribe'

Versioning

PubSubJS uses Semantic Versioning for predictable versioning.

Changelog

Please see https://github.com/mroderick/PubSubJS/releases

License

MIT: http://mrgnrdrck.mit-license.org

Alternatives

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

  • http://www.joezimjs.com/projects/publish-subscribe-jquery-plugin/
  • http://amplifyjs.com/api/pubsub/
  • http://radio.uxder.com/ β€” oriented towards 'channels', free of dependencies
  • https://github.com/pmelander/Subtopic - supports vanilla, underscore, jQuery and is even available in NuGet

Dependencies Comparison

eventemitter3

Dependencies

Dev Dependencies

@rollup/plugin-commonjs^24.0.0
@rollup/plugin-terser^0.4.0
assume^2.2.0
c8^7.3.1
mocha^10.0.0
pre-commit^1.2.0
rimraf^4.1.2
rollup^3.4.0
sauce-browsers^3.0.0
sauce-test^1.3.3

Peer Dependencies

pubsub-js

Dependencies

Dev Dependencies

@studio/changes^2.0.0
eslint4.19.1
jsdoc-to-markdown^5.0.3
mocha7.1.0
nyc15.0.0
referee^1.2.0
sinon9.0.0

Peer Dependencies

StarsIssuesVersionUpdatedβ“˜Last publish dateCreatedβ“˜Package creation dateSizeβ“˜Minified + Gzipped size
E
eventemitter3
3,438175.0.12 years ago12 years agoinstall size 1.1 KB
P
pubsub-js
4,847291.9.58 months ago12 years agoinstall size 1.1 KB

Who's Using These Packages

eventemitter3

pubsub-js

britecharts
britecharts

Composable Charting Library based on reusable D3.js components.

react-ui
react-ui

A collection of components for React, base on bootstrap 4.0.

atvjs
atvjs

Blazing fast Apple TV application development using pure JavaScript

react-foundation-apps
react-foundation-apps

Foundation Apps components built with React

efflux-tracker
efflux-tracker

Browser based music making application driving synthesizers, samplers and effects using both a tracker and piano roll/loop based interface. Supports MIDI control and provides both local and cloud based project storage.