Detalhes do pacote

PubSub

georapbox8.2kMIT4.0.1

Javascript implementation of the Publish/Subscribe pattern.

subscribe, publish, publish/subscribe, pubsub

readme (leia-me)

npm version npm license

PubSub

Javascript implementation of the Publish/Subscribe pattern.

Install

npm

$ npm install PubSub

Usage

The library is exported in UMD, CommonJS, and ESM formats. You can import it the following ways:

Using ESM import statement

import PubSub from 'PubSub';

Using CommonJS require statement

const PubSub = require('PubSub');

// If you use a bundler like Webpack, you may need to import it the following way 
// as it might try to use the ESM module instead of the CommonJS.
const PubSub = require('PubSub').default;

Old school browser global

<script src="https://cdn.jsdelivr.net/npm/PubSub@latest/dist/PubSub.umd.min.js"></script>

API

new PubSub([options])

Creates a PubSub instance.

Available options

Param Type Default Description
immediateExceptions1 boolean false Force immediate exceptions (instead of delayed exceptions).

1 Before version 3.6.0 PubSub would fail to deliver your topics to all subscribers if one or more failed (see issue #4). As of version 3.6.0 PubSub handles this by delaying thrown exceptions by default. You can set immediateExceptions to true or any truthy value in order to maintain the stack trace for development reasons but this is not recommended for production.

Public Methods

subscribe(topic, callback, [once]) ⇒ number

Subscribe to events of interest with a specific topic name and a callback function, to be executed when the topic/event is observed.

Kind: instance method of PubSub
Returns: number - The topic's token

Param Type Default Description
topic string The topic's name
callback function Callback function to execute on event, taking two arguments: - {*} data The data passed when publishing an event - {object} The topic's info (name & token)
[once] boolean false Checks if event will be triggered only one time

Example

const pubsub = new PubSub();

const onUserAdd = pubsub.subscribe('user_add', (data, topic) => {
  console.log('User added');
  console.log('user data:', data);
});

subscribeOnce(topic, callback) ⇒ number

Subscribe to events of interest setting a flag indicating the event will be published only one time.

Kind: instance method of PubSub
Returns: number - The topic's token

Param Type Description
topic string The topic's name
callback function Callback function to execute on event, taking two arguments: - {*} data The data passed when publishing an event - {object} The topic's info (name & token)

Example

const pubsub = new PubSub();

const onUserAdd = pubsub.subscribeOnce('user_add', (data, topic) => {
  console.log('User added');
  console.log('user data:', data);
});

publish(topic, [data]) ⇒ boolean

Publishes a topic asynchronously, passing the data to its subscribers.
Asynchronous publication helps in that the originator of the topics will not be blocked while consumers process them.
For synchronous topic publication check publishSync.

Kind: instance method of PubSub
Returns: boolean - Returns true if topic exists and event is published; otheriwse false

Param Type Description
topic string The topic's name
[data] ...* The data to be passed to its subscribers

Example

const pubsub = new PubSub();

pubsub.publish('user_add', {
  firstName: 'John',
  lastName: 'Doe',
  email: 'johndoe@gmail.com'
});

publishSync(topic, [data]) ⇒ boolean

Publishes a topic synchronously, passing the data to its subscribers.

Kind: instance method of PubSub
Returns: boolean - Returns true if topic exists and event is published; otheriwse false

Param Type Description
topic string The topic's name
[data] ...* The data to be passed to its subscribers

Example

const pubsub = new PubSub();

pubsub.publishSync('user_add', {
  firstName: 'John',
  lastName: 'Doe',
  email: 'johndoe@gmail.com'
});

unsubscribe(topic) ⇒ boolean | string

Unsubscribes from a specific topic, based on the topic name, or based on a tokenized reference to the subscription.

Kind: instance method of PubSub
Returns: boolean | string - Returns false if topic does not match a subscribed event; otherwise the topic's name

Param Type Description
topic string \ number Topic's name or subscription reference

Example

const pubsub = new PubSub();

// Unsubscribe using the topic's name.
pubsub.unsubscribe('user_add');

// Unsubscribe using a tokenized reference to the subscription.
pubsub.unsubscribe(onUserAdd);

unsubscribeAll() ⇒ PubSub

Clears all subscriptions whatsoever.

Kind: instance method of PubSub
Returns: PubSub - The PubSub instance.
Example

const pubsub = new PubSub();

pubsub.subscribe('message1', () => {});
pubsub.subscribe('message2', () => {});
pubsub.subscribe('message3', () => {});
pubsub.unsubscribeAll();
pubsub.hasSubscribers(); // -> false

hasSubscribers([topic]) ⇒ boolean

Checks if there are subscribers for a specific topic. If topic is not provided, checks if there is at least one subscriber.

Kind: instance method of PubSub
Returns: boolean - Returns true there are subscribers; otherwise false

Param Type Description
[topic] string The topic's name to check

Example

const pubsub = new PubSub();

pubsub.on('message', data => console.log(data));

pubsub.hasSubscribers('message');
// -> true

subscribers() ⇒ object

Gets all the subscribers as a set of key value pairs that represent the topic's name and the event listener(s) bound.

Kind: instance method of PubSub
Returns: object - A readonly object with all subscribers.
Note: Mutating the result of this method does not affect the real subscribers. This is for reference only.
Example

const pubsub = new PubSub();

pubsub.subscribe('message', listener);
pubsub.subscribe('message', listener);
pubsub.subscribe('another_message', listener);

pubsub.subscribers();
// -> Object { message: Array[2], another_message: Array[1] }

subscribersByTopic(topic) ⇒ array

Gets subscribers for a specific topic.

Kind: instance method of PubSub
Returns: array - A copy array of all subscribers for a topic if exist; otherwise an empty array
Note: Mutating the result of this method does not affect the real subscribers. This is for reference only.

Param Type Description
topic String The topic's name to check for subscribers

Example

const pubsub = new PubSub();

pubsub.subscribe('message', listener1);
pubsub.subscribeOnce('message', listener2);
pubsub.subscribe('another_message', listener1);

pubsub.subscribersByTopic('message');
// -> Array [{token: 0, once: false, callback: listener1()}, {token: 1, once: true, callback: listener2()}]

pubsub.subscribersByTopic('another_message');
// -> Array [{token: 2, once: false, callback: listener1()}]

pubsub.subscribersByTopic('some_message_not_existing');
// -> Array []

alias(aliasMap) ⇒ PubSub

Creates aliases for public methods.

Kind: instance method of PubSub
Returns: PubSub - The PubSub instance.

Param Type Description
aliasMap Object A plain object that maps the public methods to their aliases.

Example

const pubsub = new PubSub().alias({
  subscribe: 'on',
  subscribeOnce: 'once',
  publish: 'trigger',
  publishSync: 'triggerSync',
  unsubscribe: 'off',
  hasSubscribers: 'has'
});

Static methods

PubSub.createInstance([options]) ⇒ PubSub

Creates a PubSub instance. This is an alternative way to create a new instance if you don't prefer using the new keyword.

Kind: static method of PubSub
Returns: PubSub - The PubSub constructor.
Example

const pubsub = PubSub.createInstance();

Changelog

For API updates and breaking changes, check the CHANGELOG.

More about Publish/Subscribe pattern

License

The MIT License (MIT)

changelog (log de mudanças)

CHANGELOG

v4.0.1 (2025-04-05)

  • Modified README.md to update CDN links for the library.
  • Updated LICENSE to reflect the current copyright year.
  • Introduced a new .nvmrc file specifying Node.js version 20.
  • Removed CI configuration file as part of repository cleanup.

v4.0.0 (2021-24-01)

Breaking changes

  • Remove static method noConflict().

New features

  • Add a new static method createInstance() as alternative way to create a new PubSub instance.
  • Export library in UMD, ESM and CommonJS formats.

Internal changes

  • Refactor source code to ES2015+.
  • Use rollup.js to bundle the library.
  • Replace Mocha with Jest as testing framework.
  • Improve tests and coverage.
  • Replace Travis with Github Actions for CI.

v3.6.2

  • Update devDependencies
  • Update CI configuration
  • Delete examples folder

v3.6.0

  • Fix issue #4
  • Add immediateExceptions option when creating instance

v3.5.0

  • Update devDependencies
  • Use mocha and chai for testing instead of karma and jasmine
  • Drop support Bower support
  • Exclude dist folder from source control

v3.4.0

  • Add static method PubSub.noConflict() to roll back the global PubSub identifier. Used in a normal browser global namespace environment to avoid conflicts, etc.

v3.3.0

  • If there is no subscriber for a topic, delete topic property when unsubscribing. Used to leave it as an empty array before.
  • The result of subscribers and subscribersByTopic methods is just a copy of the original object or array accordingly.
  • Keep devDependencies up to date.

v3.2.7

Allow passing multiple data arguments to publish and publishSync methods.

var pubsub = new PubSub();

pubsub.subscribe('event', function (data) {
  console.log(data);
  // => Array [{fname: 'John'}, {lname: 'Doe'}, [1, 2, 3], 'Lorem ipsum dolor sit amet.']

  console.log(data[0]);
  // => Object {lname: 'John'}

  console.log(data[1]);
  // => Object {lname: 'Doe'}

  console.log(data[2]);
  // => Array [1, 2, 3]

  console.log(data[3]);
  // => String "Lorem ipsum dolor sit amet."
});

pubsub.publish('event', {fname: 'John'}, {lname: 'Doe'}, [1, 2, 3], 'Lorem ipsum dolor sit amet.');

v3.2.6

  • Ensure that listeners registered on the same topic are invoked in the order they are added.
  • Minor updates on documentation.
  • Update angular_1.x_example.

v3.2.5

  • Add working example using Angular 1.x.
  • Update devDependencies.

v3.2.4

  • Improve tests and coverage

v3.2.3

  • Return a new instance of PubSub if it is invoked without the new keyword.
  • Add code coverage.

v3.2.2

  • Keep devDependencies up to date

v3.2.1

  • Fix License

v3.2.0

  • Add public method subscribersByTopic() to get an array of subscribers for a specific topic.

v3.1.0

  • hasSubscribers checks if there is at least one subscriber, no matter its name, if no argument is passed.
  • Add public method subscribers() to get a readonly object of the current subscribers.

v3.0.0

Breaking changes

The default API method aliases are deprecated and removed from v3.0.0 onwards. However there is a new method alias introduced, that allows to create your own aliases. Therefore, if you already use those aliases in a project you can use the alias method to provide your own.

Below is a map of the default aliases that existed prior to version 3.0.0:

Original method Alias method
subscribe on
subscribeOnce once
publishSync triggerSync
unsubscribe off
hasSubscribers has

To create your own aliases:

var pubsub = new PubSub().alias({
  subscribe: 'on',
  subscribeOnce: 'once',
  publish: 'trigger',
  publishSync: 'triggerSync',
  unsubscribe: 'off',
  hasSubscribers: 'has'
});

Other updates

  • Add public method unsubscribeAll to clear all subscriptions whatsoever.
  • Add public method alias to create your own method aliases. (See above)
  • Provide source-map for the minified library.

v2.1.0

  • Add support for publishing events synchronously using publishSync method.
  • Add public method hasSubscribers to check if there are subscribers for a specific topic.

v2.0.3

  • Add support for Travis CI.
  • Lint source code using ESLint.

v2.0.2

  • Keep devDependencies up to date.

v2.0.0

Breaking changes

  • Reverse the arguments the callback function accepts, in order to allow the usage of data argument without the need to also specify the topic if not needed.
  • Throw exception if callback is not a function or is not provided at all.

Other updates

  • Return token on subscribeOnce method.
  • Correct annotations and provide examples.
  • Update devDependencies.
  • Provide npm scripts to run the tasks. No more need for global dependencies installed (Grunt).