Skip to content

Instantly share code, notes, and snippets.

@ali
Created March 1, 2016 18:40
Show Gist options
  • Save ali/23a5e95a3d1867afcd2f to your computer and use it in GitHub Desktop.
Save ali/23a5e95a3d1867afcd2f to your computer and use it in GitHub Desktop.
EventEmitterMiddleware allows your Redux actions to emit events to an external event emitter
/**
* A Redux middleware that externally emits events from actions.
* @param {EventEmitter} emitter - emits events
* @returns {Function} a Redux middleware
*/
export const eventEmitterMiddleware = (emitter) => {
if (!emitter) {
throw new Error('Cannot emit events. No EventEmitter provided.')
}
return store => next => action => {
const result = next(action)
if (!!action.meta && !!action.meta.event) {
try {
action.meta.event(emitter.emit.bind(emitter))
} catch (e) {
console.error(e)
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment