JS Built-ins
DesignPatternsadvanced

Observer β€” Unsubscribe (off)

πŸ“– Usage Example
emitter.on(handler);
emitter.off(handler);
emitter.listeners.length; // 0

off() removes a listener so it no longer receives future events.

Observer Pattern β€” Unsubscribe

Subscribers should be able to unsubscribe from events using an off() or unsubscribe() method.

Challenge: Implement an EventEmitter with an off(eventName, callback) method that removes a listener.

Example:

const emitter = new EventEmitter()
const handler = () => { console.log('fired') }
emitter.on('test', handler)
emitter.off('test', handler)
emitter.emit('test') // handler does not execute
πŸ’‘ Hints (3)
  • β€’ Use filter to remove listener that matches the reference
  • β€’ Compare function references with ===
  • β€’ Only the exact function reference should be removed