Event Emitter Pattern in JavaScript
Level 4317 keystrokes
The Event Emitter pattern allows objects to subscribe to and emit custom events.
JavaScript code
// Simple EventEmitter class implementation1class EventEmitter { // Initialize events object in constructor2 constructor() { this.events = {}; } // Subscribe: create the event's list with ||= if needed, then add the callback3 on(event, fn) { (this.events[event] ||= []).push(fn); } // Emit: call every registered callback with data (|| [] handles events with no listeners)4 emit(event, data) { (this.events[event] || []).forEach(fn => fn(data)); }5}// Create an instance6const emitter = new EventEmitter();// Subscribe to "greet" event7emitter.on("greet", name => console.log(`Hello, ${name}!`));// Emit "greet" event with "World" as data8emitter.emit("greet", "World");Output
Hello, 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.
(× 12)× 12.× 8;× 6"× 6{× 6}× 6,× 5=× 5[× 4