Skip to content
BENIBIX Learn

Observer Pattern

Development🏗️ ArchitectureDesign Patterns

Also known as Observer, Listener Pattern, Event Listener

One object keeps a list of others. It tells them all when it changes.

Think of it like

Think of it like a shop's mailing list. When new stock comes in, all on the list get told.

Example

Lucy's page has a button. Two pieces of code each call addEventListener on it. When the button is clicked, both run.

Why it matters

The watched object does not need to know who is listening. So new listeners can join with ease.

Definition

The observer pattern lets one object tell many others when something about it changes. The object being watched keeps a list of observers. Any part of the program can add itself to that list. When a change happens, the object calls each observer in turn. Event listeners in a web browser are the best-known use of it.

Example code

javascript
button.addEventListener('click', () => save());
button.addEventListener('click', () => track('saved'));
// one click: both functions run
Two observers sign up to the same button, and one click runs both.

Common mistake

Adding observers and never removing them. Each one keeps old objects in memory, which causes leaks.

Key takeaways

  1. 1
    One tells many. On every change.
  2. 2
    Sign up to listen. Add to the list.
  3. 3
    Remember to leave. Or memory leaks.