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 observers1class Subject { // Constructor initializes empty observers array2 constructor() {3 this.observers = [];4 } // subscribe adds a callback and returns unsubscribe function5 subscribe(fn) { // Add the callback to observers list6 this.observers.push(fn); // Return a function that removes this observer when called7 return () => this.observers = this.observers.filter(o => o !== fn);8 } // notify calls all observers with the data9 notify(data) { // Execute each observer function with the data10 this.observers.forEach(fn => fn(data));11 }12}13 // Create a subject instance14const subject = new Subject();// Subscribe first observer, save unsubscribe function15const unsub = subject.subscribe(d => console.log("A:", d));// Subscribe second observer16subject.subscribe(d => console.log("B:", d));// Notify all: both A and B receive "Hello"17subject.notify("Hello");// Unsubscribe A18unsub();// Notify: only B receives "World"19subject.notify("World");Output
A: Hello B: Hello B: 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=× 11;× 10"× 8>× 5{× 4}× 4,× 2