React Event Emitter

--

Inspired by https://lolahef.medium.com/react-event-emitter-9a3bb0c719

function createEventEmitter() {
return {
subscriptions: new Set(),
emit(value) {
for (const callback of this.subscriptions) {
callback(value);
}
},
subscribe(callback) {
this.subscriptions.add(callback);
return () => {
this.subscriptions.delete(callback);
};
},
};
}
const eventEmitter = createEventEmitter();const unsubscribe = eventEmitter.subscribe(console.log);eventEmitter.emit(1);
eventEmitter.emit(2);
eventEmitter.emit(3);
const dispatch = (action) => eventEmitter.emit(action);dispatch({type: 'EVENT_NAME', payload: 'Some data'});unsubscribe();eventEmitter.emit('No console.log we are unsubscribed.');

--

--