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 pattern1class Observable { // Initialize with empty observers list2 constructor() { this.observers = []; } // Subscribe adds an observer and returns unsubscribe function3 subscribe(fn) {4 this.observers.push(fn); // Return a function to remove this observer5 return () => this.observers = this.observers.filter(o => o !== fn);6 } // Notify all observers with data7 notify(data) {8 this.observers.forEach(fn => fn(data));9 }10}11 // Create an observable instance12const observable = new Observable();// Subscribe two observers, keep unsubscribe functions13const 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 116unsub1();// Notify again - only observer 2 receives "World"17observable.notify("World");Output
Observer 1: Hello Observer 2: Hello Observer 2: World
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