Observable Pattern in JavaScript

Level 5481 keystrokes

The Observable pattern allows multiple observers to subscribe and react to notifications.

JavaScript code

// Observable class for publish-subscribe pattern
1class Observable {
// Initialize with empty observers list
2 constructor() { this.observers = []; }
// Subscribe adds an observer and returns unsubscribe function
3 subscribe(fn) {
4 this.observers.push(fn);
// Return a function to remove this observer
5 return () => this.observers = this.observers.filter(o => o !== fn);
6 }
// Notify all observers with data
7 notify(data) {
8 this.observers.forEach(fn => fn(data));
9 }
10}
11
// Create an observable instance
12const observable = new Observable();
// Subscribe two observers, keep unsubscribe functions
13const unsub1 = observable.subscribe(d => console.log(`Observer 1: ${d}`));
14const unsub2 = observable.subscribe(d => console.log(`Observer 2: ${d}`));
// Notify all - both receive "Hello"
15observable.notify("Hello");
// Unsubscribe observer 1
16unsub1();
// Notify again - only observer 2 receives "World"
17observable.notify("World");

Output

Observer 1: Hello
Observer 2: Hello
Observer 2: 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
  • =× 12
  • ;× 10
  • {× 6
  • }× 6
  • >× 5
  • "× 4
  • `× 4

More JavaScript examples at level 5

← JavaScript typing practice