- Published on
Event Emitter
Simple Event Emitter or PubSub pattern
class Event { constructor() { this.events = {}; }
subscribe(event, handler) { this.events[event] = this.events[event] || []; this.events[event].push(handler); return () => this.unSubscribe(event, handler) }
unSubscribe(event, handler) { const handlers = this.events[event]; if (handlers && Array.isArray(handlers)) { for (let i = 0; i < handlers.length; i++) { if (handlers[i] === handler) { handlers.splice(i, 1); break; } } } }
emit(event, ...args) { (this.events[event] || []).forEach((handler) => { handler(...args); }); }}
Usage
// Create a global instance in your appconst globalEvent = new Event()
const handler1 = data => console.log(`handler1(): FOO event emiited with data: ${data}`)const handler2 = data => console.log(`handler2(): FOO event emiited with data: ${data}`)
// Subscribe to eventglobalEvent.subscribe('FOO', handler1)globalEvent.subscribe('FOO', handler2)
// Emit event when neededglobalEvent.emit('FOO', 'foo')
// Expected:// handler1(): FOO event emiited with data: foo// handler2(): FOO event emiited with data: foo
// Unsubscribe eventglobalEvent.unSubscribe('FOO', handler2)
// ThenglobalEvent.emit('FOO', 'bar')
// Expected:// handler1(): FOO event emiited with data: bar