JS Built-ins
DesignPatternsbeginner

Observer β€” Basic subscription

πŸ“– Usage Example
const emitter = {
  handlers: [],
  on(fn) { this.handlers.push(fn); },
  emit(v) { this.handlers.forEach(h => h(v)); }
};
emitter.on(v => console.log(v));
emitter.emit('hello');

The Observer pattern lets objects subscribe to events emitted by a subject.

Observer Pattern β€” Basic Subscription

The Observer pattern allows objects to subscribe to events and be notified when those events occur.

Challenge: Implement an EventEmitter class with:

  • on(eventName, callback) - subscribe to an event
  • emit(eventName, ...args) - trigger an event

When an event is emitted, all subscribers should be called with the provided arguments.

Example:

const emitter = new EventEmitter()
let result = null
emitter.on('test', (value) => { result = value })
emitter.emit('test', 'hello')
result // 'hello'
πŸ’‘ Hints (3)
  • β€’ Use an object to store listeners by event name
  • β€’ Use nullish coalescing (??) to initialize array if needed
  • β€’ forEach over all listeners for an event and call them