Observer Pattern in JavaScript

Level 5421 keystrokes

Implements the Observer pattern with subscribe, unsubscribe, and notify functionality.

JavaScript code

// Subject class manages a list of observers
1class Subject {
// Constructor initializes empty observers array
2 constructor() {
3 this.observers = [];
4 }
// subscribe adds a callback and returns unsubscribe function
5 subscribe(fn) {
// Add the callback to observers list
6 this.observers.push(fn);
// Return a function that removes this observer when called
7 return () => this.observers = this.observers.filter(o => o !== fn);
8 }
// notify calls all observers with the data
9 notify(data) {
// Execute each observer function with the data
10 this.observers.forEach(fn => fn(data));
11 }
12}
13
// Create a subject instance
14const subject = new Subject();
// Subscribe first observer, save unsubscribe function
15const unsub = subject.subscribe(d => console.log("A:", d));
// Subscribe second observer
16subject.subscribe(d => console.log("B:", d));
// Notify all: both A and B receive "Hello"
17subject.notify("Hello");
// Unsubscribe A
18unsub();
// Notify: only B receives "World"
19subject.notify("World");

Output

A: Hello
B: Hello
B: World
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • (× 16
  • )× 16
  • .× 14
  • =× 11
  • ;× 10
  • "× 8
  • >× 5
  • {× 4
  • }× 4
  • ,× 2

More JavaScript examples at level 5

← JavaScript typing practice