📌 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() {
this.observers = []; // List of observers
attach(observer) {
this.observers.push(observer); // Add an observer
detach(observer) {
this.observers = this.observers.filter(obs => obs !== observer); // Remove an
observer
notify(data) {
this.observers.forEach(observer => observer.update(data)); // Notify all observers
}
// Observer
class Observer {
constructor(name) {
this.name = name;
update(data) {
console.log(`${this.name} received update: ${data}`);
// Usage
const subject = new Subject();
const observer1 = new Observer("Observer 1");
const observer2 = new Observer("Observer 2");
subject.attach(observer1);
subject.attach(observer2);
subject.notify("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() {
this.events = {}; // Store event names and their listeners
subscribe(eventName, callback) {
if (!this.events[eventName]) {
this.events[eventName] = []; // Initialize event list
this.events[eventName].push(callback);
unsubscribe(eventName, callback) {
if (this.events[eventName]) {
this.events[eventName] = this.events[eventName].filter(cb => cb !== callback);
publish(eventName, data) {
if (this.events[eventName]) {
this.events[eventName].forEach(callback => callback(data));
// Usage
const eventBus = new PubSub();
function subscriber1(data) {
console.log(`Subscriber 1 received: ${data}`);
function subscriber2(data) {
console.log(`Subscriber 2 received: ${data}`);
eventBus.subscribe("news", subscriber1);
eventBus.subscribe("news", subscriber2);
eventBus.publish("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 (Node.js 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? 🚀