logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Implementing Pub/Sub Pattern in JavaScript

author
Written by
Abhishek Goyan

12/09/2024

JavaScript

Sign in to read full article

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:

  1. Publisher: This component publishes messages to a topic or channel.
  2. 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.

  1. Subscribing to an Event:
// Subscribe to the user logged in event pubSub.subscribe('user_logged_in', (data) => { console.log(`Welcome, ${data.username}!`); });
  1. 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.

  1. 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.

Popular Tags

JavaScriptPub/SubDesign Pattern

Share now!

Like & Bookmark!

Related Collections

  • JavaScript Interview Mastery: 20 Essential Concepts

    22/10/2024 | VanillaJS

  • JavaScript Coding Challenges for Interviews

    14/09/2024 | VanillaJS

  • JavaScript Mastery: From Basics to Advanced Techniques

    15/10/2024 | VanillaJS

Related Articles

  • Creating a Promise-Based API Request Function

    14/09/2024 | VanillaJS

  • Understanding JavaScript Symbols

    22/10/2024 | VanillaJS

  • Deep Cloning Object in JavaScript

    25/07/2024 | VanillaJS

  • Understanding Closures in JavaScript

    21/07/2024 | VanillaJS

  • Flatten a Nested Array Without Using the Flat Function

    14/09/2024 | VanillaJS

  • Optimizing JavaScript Performance with a Memoization Function

    14/09/2024 | VanillaJS

  • Implementing Event Delegation for DOM Events

    14/09/2024 | VanillaJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design