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 implementation
1class EventEmitter {
// Initialize events object in constructor
2 constructor() { this.events = {}; }
// Subscribe: create the event's list with ||= if needed, then add the callback
3 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 instance
6const emitter = new EventEmitter();
// Subscribe to "greet" event
7emitter.on("greet", name => console.log(`Hello, ${name}!`));
// Emit "greet" event with "World" as data
8emitter.emit("greet", "World");

Output

Hello, 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.

  • (× 12
  • )× 12
  • .× 8
  • ;× 6
  • "× 6
  • {× 6
  • }× 6
  • ,× 5
  • =× 5
  • [× 4

More JavaScript examples at level 4

← JavaScript typing practice