Question 85
Question
Explain how to implement a basic pub/sub system from scratch.
Answer
Here's how to build a simple pub/sub (publish-subscribe) system in JavaScript, allowing components to communicate asynchronously:
Core Concepts:
Publisher: An object that emits events or "messages" (the "publication").
Subscriber: An object that listens for specific events and executes code when they occur (the "subscription").
Implementation:
Explanation:
PubSub
Class: This class manages all the events and subscribers.events
: An object where keys are event names (strings) and values are arrays of callback functions that listen for those events.
subscribe(eventName, callback)
:Takes an
eventName
and acallback
function as arguments.If the event doesn't exist yet, it creates a new array in the
events
object to store subscribers for that event.Adds the
callback
to the appropriate array of subscribers.
publish(eventName, data)
:Takes an
eventName
and some optionaldata
as arguments.Checks if there are any subscribers for the given
eventName
.If there are, it iterates through the array of subscribers and calls each callback function with the provided
data
.
Key Points:
Asynchronous Communication: Subscribers don't execute immediately when an event is published; they run later when their respective callbacks are called.
Loose Coupling: Publishers and subscribers don't directly know about each other. They only interact through events, making your code more modular and maintainable.
Last updated