MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Observer & Pub/Sub Pattern0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
9.1Singleton Pattern & Module Pattern9.2Factory & Builder Patterns9.3Observer & Pub/Sub Pattern9.4Strategy & State Patterns9.5Proxy & Decorator Patterns
HomeTutorialsJavaScript for AdvancedObserver & Pub/Sub Pattern
Strategy & State Patterns

Observer & Pub/Sub Pattern

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

Event-driven programming is central to modern JavaScript architecture. The Observer Pattern and the Publish-Subscribe (Pub/Sub) Pattern allow objects to notify other parts of an application about state changes without tight coupling. While often confused, they have distinct architectural topologies.


1. Observer vs. Pub/Sub: The Key Difference

1Observer Pattern (Direct Coupling):
2 [ Subject (Observable) ] ──Direct Reference──► [ Observer 1 ]
3 ──Direct Reference──► [ Observer 2 ]
4 
5Pub/Sub Pattern (Decoupled via Message Broker / Event Bus):
6 [ Publisher ] ──► [ Event Bus / Broker ] ──► [ Subscriber A ]
7 ──► [ Subscriber B ]
  • Observer Pattern: The Subject maintains a direct internal list of Observers and invokes their update methods directly.
  • Pub/Sub Pattern: Publishers and Subscribers never know each other exist; they communicate exclusively through an intermediate Event Bus / Message Channel.

2. Implementing the Observer Pattern

1// The Subject (Observable)
2class StockTicker {
3 constructor(symbol) {
4 this.symbol = symbol;
5 this.price = 0;
6 this.observers = [];
7 }
8 
9 // Register observer
10 subscribe(observer) {
11 this.observers.push(observer);
12 }
13 
14 // Unregister observer
15 unsubscribe(observer) {
16 this.observers = this.observers.filter(obs => obs !== observer);
17 }
18 
19 // Notify all observers
20 notify() {
21 this.observers.forEach(obs => obs.update(this.symbol, this.price));
22 }
23 
24 updatePrice(newPrice) {
25 this.price = newPrice;
26 this.notify();
27 }
28}
29 
30// Observers
31class MobileAlertObserver {
32 update(symbol, price) {
33 console.log(`[Mobile Push]: ${symbol} moved to $${price}`);
34 }
35}
36 
37class TradingBotObserver {
38 update(symbol, price) {
39 if (price < 150) console.log(`[Trading Bot]: BUY order placed for ${symbol}!`);
40 }
41}
42 
43const appleStock = new StockTicker('AAPL');
44const mobileUser = new MobileAlertObserver();
45const bot = new TradingBotObserver();
46 
47appleStock.subscribe(mobileUser);
48appleStock.subscribe(bot);
49 
50appleStock.updatePrice(145);
51// Logs both: Mobile Push and Trading Bot BUY order!

3. Implementing a Production-Grade Pub/Sub EventBus

1class EventBus {
2 constructor() {
3 this.events = new Map();
4 }
5 
6 // Subscribe to an event topic
7 on(topic, handler) {
8 if (!this.events.has(topic)) {
9 this.events.set(topic, new Set());
10 }
11 this.events.get(topic).add(handler);
12 
13 // Return an unsubscribe function
14 return () => this.off(topic, handler);
15 }
16 
17 // Unsubscribe
18 off(topic, handler) {
19 if (this.events.has(topic)) {
20 this.events.get(topic).delete(handler);
21 }
22 }
23 
24 // Publish event payload to topic
25 emit(topic, payload) {
26 if (this.events.has(topic)) {
27 this.events.get(topic).forEach(handler => {
28 try {
29 handler(payload);
30 } catch (error) {
31 console.error(`Error in event listener for "${topic}":`, error);
32 }
33 });
34 }
35 }
36 
37 // Subscribe to fire once only
38 once(topic, handler) {
39 const unsub = this.on(topic, (data) => {
40 unsub();
41 handler(data);
42 });
43 }
44}
45 
46// Global Singleton Event Bus instance
47export const eventBus = new EventBus();

Clean Decoupled Usage:

1// In CartComponent.js:
2eventBus.emit('cart:updated', { itemCount: 3, total: 95.00 });
3 
4// In NavbarBadge.js (Doesn't care who emitted it!):
5eventBus.on('cart:updated', (data) => {
6 badgeElement.textContent = data.itemCount;
7});

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary architectural difference between the Observer and Pub/Sub patterns?
Question 2
Why does an EventBus on() method typically return an unsubscribe function?
Question 3
What collection type is ideal for storing listeners per event topic to avoid duplicate registrations?
Question 4
What does eventBus.once(topic, handler) do?
Question 5
What is a potential hazard of using global Pub/Sub Event Buses in large Single Page Applications?
Next Lesson

Strategy & State Patterns

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Factory & Builder PatternsStrategy & State Patterns

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext