WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 49 of 100

How do you implement a pub-sub pattern in JavaScript?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

The Pub-Sub (publish-subscribe) pattern is a design pattern that allows you to build applications where different components can communicate with each other without having direct dependencies on each other. In this pattern, components can "publish" messages (or events) and other components can "subscribe" to those messages and be notified when they occur. Here’s an example of how to implement a basic pub-sub pattern in JavaScript:

    // Define a pubsub object
    const pubsub = {};
    
    // Define an event list
    pubsub.events = {};
    
    // Define a publish function
    pubsub.publish = function(event, data) {
        if (!this.events[event]) {
            return;
        }
        this.events[event].forEach(function(callback) {
            callback(data);
        });
    };
    
    // Define a subscribe function
    pubsub.subscribe = function(event, callback) {
        if (!this.events[event]) {
            this.events[event] = [];
        }
        this.events[event].push(callback);
    };
    
    // Usage example
    function handleData(data) {
        console.log(data);
    }
    
    pubsub.subscribe('data', handleData);
    
    setTimeout(function() {
        pubsub.publish('data', {message: 'hello world'});
    }, 1000);

In this example, we define a pubsub object that has an events property which is an object that stores arrays of callback functions for each event. The publish function takes an event name and some data, looks up the corresponding array of callbacks, and calls each of them with the data. The subscribe function takes an event name and a callback function and adds the callback to the appropriate array in the events object.

In the usage example, we define a handleData function and subscribe it to the data event using pubsub.subscribe. We then use setTimeout to simulate an asynchronous operation and publish the data event with some data using pubsub.publish. When the data event is published, the handleData function is called with the data and logs it to the console.

This is a simple example of how to implement a pub-sub pattern in JavaScript, but it can be extended and customized to fit more complex use cases.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics