JavaScript Course
JavaScript
/
Advanced

Publish-Subscribe Pattern

Definition

A messaging pattern where senders (Publishers) do not program the messages to be sent directly to specific receivers (Subscribers). Instead, published messages are categorized into channels via a central Event Bus.

Explain Like I'm New

Pub-Sub is a radio station. The radio DJ (Publisher) broadcasts music on frequency 99.5 FM. They have no idea who is listening. You (Subscriber) tune your car radio to 99.5 FM. If 100 people tune in, everyone hears the song. If nobody tunes in, the DJ still plays the song. The DJ and the listeners never actually meet; the Radio Tower (Event Bus) connects them.

Real World Example

Redux. A component dispatches an action (Publisher). The Redux Store (Event Bus) receives it. Any component that mapped that state (Subscriber) automatically updates. Also used in WebSockets and Node.js EventEmitters.

Common Use Cases

  • •Decoupling massive applications
  • •Global state management systems
  • •Microservices communication

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is the 'Event Bus'?

intermediate

  • What is the primary difference between Pub-Sub and Observer?

advanced

  • What is the main downside of a heavily Pub-Sub architecture?

Flash Cards

Question

What is the Event Bus?

Click to reveal answer
Answer

It is the middleman. A simple JavaScript object that holds a dictionary of topics (channels) and an array of callbacks for each topic. `events = { 'USER_LOGIN': [cb1, cb2] }`.

Question

What is the main downside?

Click to reveal answer
Answer

It can be impossible to debug. Because components are perfectly decoupled, tracing the flow of data is a nightmare. A button is clicked, an event is fired into the void, and somehow a deeply nested component changes state. Without good dev tools, finding the connection is very difficult.