Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Event Emitter

Object-Oriented Programmingmedium

Course · Section 14: Object-Oriented Programming (OOP) With JavaScript · Lecture 226: ES6 Classes

Build a tiny event emitter (publish/subscribe). Implement `EventEmitter`: - `on(event, listener)` registers a listener. - `off(event, listener)` removes a listener. - `emit(event, ...args)` calls every listener for the event with the args.

Examples

Input: on('data', fn); emit('data', 1); emit('data', 2); off('data', fn); emit('data', 3)
Output: [1, 2]
fn collects 1 and 2; after off, the third emit calls nothing.

Sample tests

Input: on, emit twice, off, emit again
Output: [1,2]
Input: multiple listeners
Output: ["a","b"]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • off must remove the exact same function reference.
  • emit on an event with no listeners should be a safe no-op.
Approach & explanation (try first)

A map from event name to listener arrays implements pub/sub: on appends, off filters by reference, and emit invokes each with the forwarded arguments.

Loading...
⌘/Ctrl + Enter

Run your code to see results.