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.
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 eventemit(eventName, ...args) - trigger an eventWhen 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'