The Publish/Subscribe (Pub/Sub) pattern is a messaging pattern where senders (publishers) transmit messages to one or more subscribers without needing to know who those subscribers are. This leads to greater flexibility and a decoupled architecture.
In a traditional event-driven architecture, components might need to reach out directly to one another to send messages; however, in a Pub/Sub architecture, you can simplify interactions. Instead of tightly coupling components, events can be published, and any interested subscribers can listen to those events and respond accordingly.
How It Works
The Pub/Sub pattern contains two main actors:
- Publisher: This component publishes messages to a topic or channel.
- Subscriber: This component subscribes to a channel to receive messages.
When a message is published, all the subscribers of that channel are notified. This pattern decouples the publisher from the subscriber, allowing for more flexible and testable code.
Setting Up Pub/Sub in JavaScript
Creating the Pub/Sub System
Let's create a simple Pub/Sub system in JavaScript:
class PubSub { constructor() { this.subscribers = {}; } subscribe(event, callback) { if (!this.subscribers[event]) { this.subscribers[event] = []; } this.subscribers[event].push(callback); } publish(event, data) { if (this.subscribers[event]) { this.subscribers[event].forEach(callback => callback(data)); } } unsubscribe(event, callback) { if (!this.subscribers[event]) return; this.subscribers[event] = this.subscribers[event].filter(subscriber => subscriber !== callback); } } const pubSub = new PubSub();
How to Use
Now that we have our Pub/Sub system set up, let's see how we can use it in practice.
Example: User Login Notification
Let's say we want to notify other parts of our application when a user successfully logs in. We can achieve this using our Pub/Sub system.
- Subscribing to an Event:
// Subscribe to the user logged in event pubSub.subscribe('user_logged_in', (data) => { console.log(`Welcome, ${data.username}!`); });
- Publishing an Event:
When our user logs in, we will publish the event:
// Simulating a user login const userData = { username: 'JohnDoe', email: 'john@example.com' }; // Publish the user logged in event pubSub.publish('user_logged_in', userData);
When the above publish method is called, it triggers the subscriber, and you’ll see "Welcome, JohnDoe!" logged to the console.
- Unsubscribing from an Event:
If after some condition, you want a subscriber to stop receiving notifications, you can unsubscribe it:
const welcomeCallback = (data) => { console.log(`Welcome, ${data.username}!`); }; // Subscribe pubSub.subscribe('user_logged_in', welcomeCallback); // Unsubscribe pubSub.unsubscribe('user_logged_in', welcomeCallback);
In this example, welcomeCallback
will no longer receive notifications for user_logged_in
events.