📌 Observer vs.
Pub-Sub Pattern in JavaScript
Both Observer and Publisher-Subscriber (Pub-Sub) are design patterns used for
managing event-driven architectures. They allow different parts of an application
to communicate without being tightly coupled.
🔹 1. Observer Pattern
📌 What is it?
The Observer Pattern defines a one-to-many relationship where multiple
observers (subscribers) watch a subject (publisher) and get notified when a
state change occurs.
📌 How It Works?
1. The Subject maintains a list of Observers.
2. Observers can subscribe (attach) or unsubscribe (detach) from the subject.
3. When the subject's state changes, all subscribers are notified.
📌 Example: Simple Observer Pattern
class Subject {
constructor() {
[Link] = []; // List of observers
attach(observer) {
[Link](observer); // Add an observer
detach(observer) {
[Link] = [Link](obs => obs !== observer); // Remove an
observer
notify(data) {
[Link](observer => [Link](data)); // Notify all observers
}
// Observer
class Observer {
constructor(name) {
[Link] = name;
update(data) {
[Link](`${[Link]} received update: ${data}`);
// Usage
const subject = new Subject();
const observer1 = new Observer("Observer 1");
const observer2 = new Observer("Observer 2");
[Link](observer1);
[Link](observer2);
[Link]("Event Triggered!");
// Observer 1 received update: Event Triggered!
// Observer 2 received update: Event Triggered!
✅ Use Cases:
UI components reacting to data changes (e.g., React state updates).
Notification systems.
Event-driven programming (like DOM event listeners).
🔹 2. Publisher-Subscriber (Pub-Sub) Pattern
📌 What is it?
The Pub-Sub Pattern introduces an intermediary Event Bus (Message Broker)
that decouples publishers and subscribers.
Publishers send messages/events to the event bus.
Subscribers listen for specific events and execute actions when they occur.
📌 How is it different from Observer?
In Observer, the subject maintains a list of subscribers directly.
In Pub-Sub, the publisher & subscriber never know about each other—they
communicate via a third-party event bus.
📌 Example: Pub-Sub Using an Event Bus
class PubSub {
constructor() {
[Link] = {}; // Store event names and their listeners
subscribe(eventName, callback) {
if (![Link][eventName]) {
[Link][eventName] = []; // Initialize event list
[Link][eventName].push(callback);
unsubscribe(eventName, callback) {
if ([Link][eventName]) {
[Link][eventName] = [Link][eventName].filter(cb => cb !== callback);
publish(eventName, data) {
if ([Link][eventName]) {
[Link][eventName].forEach(callback => callback(data));
// Usage
const eventBus = new PubSub();
function subscriber1(data) {
[Link](`Subscriber 1 received: ${data}`);
function subscriber2(data) {
[Link](`Subscriber 2 received: ${data}`);
[Link]("news", subscriber1);
[Link]("news", subscriber2);
[Link]("news", "Breaking News: JavaScript is awesome!");
// Subscriber 1 received: Breaking News: JavaScript is awesome!
// Subscriber 2 received: Breaking News: JavaScript is awesome!
✅ Use Cases:
Event-driven systems ([Link] EventEmitter, Redux).
Chat applications (where multiple users subscribe to messages).
Logging and Analytics (listening for user interactions).
🔹 Observer vs. Pub-Sub: Key Differences
Feature Observer Pattern Pub-Sub Pattern
Direct Observers directly subscribe to Publishers & subscribers don't know
Dependency the subject each other
Communicatio One-to-Many (directly
Many-to-Many (via event bus)
n notified)
Low (Observers know about High (Intermediary handles
Decoupling
Subject) communication)
Complexity Simple More scalable for large applications
Example Use Messaging, Event-driven
UI updates, DOM Events
Case architecture
🚀 Conclusion
✅ Use Observer Pattern when objects need to directly listen for updates
(e.g., UI changes).
✅ Use Pub-Sub Pattern for scalability and flexibility, especially in large
applications with loosely coupled components.
Would you like a diagram to illustrate these patterns visually? 🚀