12/09/2024
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.
The Pub/Sub pattern contains two main actors:
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.
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();
Now that we have our Pub/Sub system set up, let's see how we can use it in practice.
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.
// Subscribe to the user logged in event pubSub.subscribe('user_logged_in', (data) => { console.log(`Welcome, ${data.username}!`); });
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.
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.
15/10/2024 | VanillaJS
22/10/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
22/10/2024 | VanillaJS
26/07/2024 | VanillaJS
21/07/2024 | VanillaJS
14/09/2024 | VanillaJS
22/10/2024 | VanillaJS
22/10/2024 | VanillaJS