Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // object to store the listeners grouped by actionTypes
- const listenersMap = {};
- /**
- * The middleware
- * example usage: createStore(rootReducer, applyMiddleware(thunk, reduxActionListener, reduxLogger))
- */
- export const reduxActionListener = store => next => action => {
- // store the prev state to keep it for the listener
- const prevState = store.getState();
- // make sure the original action runs first, so errors won't prevent from running
- const result = next(action);
- // notify all listeners that attached to the type
- const listeners = listenersMap[action.type];
- if (listeners) {
- // eslint-disable-next-line no-console
- console.log(`[ActionListener] Notifying ${listeners.length} listener(s) of action: ${action.type}`);
- const params = { action, state: store.getState(), prevState, store };
- for (const listener of listeners) {
- listener(params);
- }
- }
- // important: return the original result
- return result;
- };
- /**
- * Adds an action listener callback on the specified action type
- * @param {string} actionType
- * @param {listenerFn} function
- * @return the remove function
- */
- export const addActionListener = (actionType, listenerFn) => {
- const listeners = listenersMap[actionType] || (listenersMap[actionType] = []);
- listeners.push(listenerFn);
- return () => {
- const index = listeners.indexOf(listenerFn);
- if (index > -1) {
- listeners.splice(index, 1);
- }
- };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement