FrontendInterviews.dev

Loading problem…

3. Event Emitter

Medium•
Acceptance: 62.86%
•
🔓3/3 Pro unlocks today

Implement an EventEmitter class with on, off, and emit methods for event handling.

Requirements

1. Basic Functionality

  • on(event, handler): Register an event handler
  • off(event, handler): Remove an event handler
  • emit(event, ...args): Emit an event with arguments
  • Support multiple handlers for same event
  • Pass arguments to handlers

Example Usage

const emitter = new EventEmitter();

emitter.on('click', (x, y) => {
  console.log(`Clicked at (${x}, ${y})`);
});

emitter.emit('click', 10, 20); // Logs: Clicked at (10, 20)

Constraints

  • Support multiple handlers for same event
  • Remove specific handler with off()
  • Pass all arguments to handlers
  • Handle events with no handlers