Course contentsShow
← JavaScript
Lesson 2110 of 2,72344. Reactive PatternsFree lesson

Implementing Observers

Create observer objects that react to subject notifications by executing callback functions or updating state.

Implementing Observers

You'll learn how to create observer objects that respond to subject notifications by executing callbacks or updating their own state.

What Is an Observer Object?

An observer is any object that registers itself with a subject to receive notifications when something changes. When the subject calls notify(), each observer's update() method gets triggered. The observer then decides what to do—run a callback, update internal state, log something, or trigger side effects.

Building a Basic Observer

An observer typically implements an update() method that receives data from the subject:

class Logger {
  update(data) {
    console.log(`[LOG] Event occurred:`, data);
  }
}

class Dashboard {
  constructor() {
    this.value = null;
  }

  update(data) {
    this.value = data.temperature;
    console.log(`Dashboard updated: ${this.value}°C`);
  }
}

Both objects follow the observer interface—they have an update() method. The subject doesn't care what they do internally; it just calls update() on each registered observer.

Connecting Observers to a Subject

const sensor = new TemperatureSensor();
const logger = new Logger();
const dashboard = new Dashboard();

sensor.attach(logger);
sensor.attach(dashboard);

sensor.setTemperature(22); 
// Logs from both logger and dashboard

When setTemperature() triggers notify(), both observers react independently. The logger outputs to console, the dashboard stores the value—each handles the notification differently based on its purpose.

Key Takeaway:
Observers implement an update() method to react to subject notifications, allowing multiple independent components to respond to state changes without the subject needing to know their implementation details.