What is nano-pubsub?
nano-pubsub is a lightweight publish-subscribe (pub/sub) library for JavaScript. It allows you to create a simple event-driven architecture where you can publish events and subscribe to them, making it easier to manage communication between different parts of your application.
What are nano-pubsub's main functionalities?
Creating a PubSub instance
This code demonstrates how to create a new instance of the PubSub class from the nano-pubsub package. This instance will be used to manage event subscriptions and publications.
const PubSub = require('nano-pubsub');
const pubsub = new PubSub();
Subscribing to an event
This code shows how to subscribe to an event named 'eventName'. The callback function will be called whenever the event is published, and it will receive the published data as an argument.
const subscription = pubsub.subscribe('eventName', (data) => {
console.log('Event received:', data);
});
Publishing an event
This code demonstrates how to publish an event named 'eventName' with some data. All subscribers to this event will receive the data.
pubsub.publish('eventName', { key: 'value' });
Unsubscribing from an event
This code shows how to unsubscribe from an event. After calling unsubscribe, the callback function will no longer be called when the event is published.
subscription.unsubscribe();
Other packages similar to nano-pubsub
eventemitter3
eventemitter3 is a high-performance EventEmitter for Node.js and the browser. It provides a similar pub/sub mechanism but with more features and better performance. It is more suitable for applications that require a robust event handling system.
mitt
mitt is a tiny (~200 bytes) functional event emitter. It offers a similar pub/sub pattern but is designed to be extremely lightweight and simple. It is ideal for small projects or when you need a minimal event system.
nano-pubsub
Tiny (<0.5 kb) publish/subscribe
Install
npm install nano-pubsub
Usage example
import createPubsub from 'nano-pubsub'
const events = createPubsub()
const unsubscribe = events.subscribe(value => {
console.log('got value:', value)
})
events.publish('Hello')
events.publish('World')
unsubscribe()
events.publish('Something')