redux-listen
Version:
Use the listener pattern with Redux middleware.
106 lines (90 loc) • 2.54 kB
JavaScript
;
var REDUX_LISTEN_RESOLVE = 'REDUX_LISTEN_RESOLVE';
module.exports = function createReduxListen() {
var listeners = [];
var pendingCount = 0;
function getListeners() {
return listeners;
}
function isPending() {
return pendingCount > 0;
}
function addListener(type, fn) {
listeners.push({
fn: fn,
type: type,
isRegExp: type instanceof RegExp
});
return fn;
}
function addListeners(obj) {
Object.keys(obj).map(function (type) {
return addListener(type, obj[type]);
});
return obj;
}
function removeListeners() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
type = _ref.type,
fn = _ref.fn;
listeners = listeners.filter(function (_) {
return type && _.type !== type || fn && _.fn !== fn;
});
return listeners;
}
function decrementPendingCount(dispatch) {
var called = false;
return function () {
if (called) return pendingCount;
called = true;
pendingCount -= 1;
if (pendingCount <= 0) {
pendingCount = 0;
dispatch({
type: REDUX_LISTEN_RESOLVE
});
}
return pendingCount;
};
}
var middleware = function middleware(store) {
return function (next) {
return function (action) {
var result = next(action);
try {
var getState = store.getState,
dispatch = store.dispatch;
var matches = listeners.filter(function (_ref2) {
var type = _ref2.type,
isRegExp = _ref2.isRegExp;
return type === '*' || (isRegExp ? action.type.match(type) : type === action.type);
});
pendingCount += matches.filter(function (_ref3) {
var fn = _ref3.fn;
return fn.length > 1;
}).length;
matches.map(function (_ref4) {
var fn = _ref4.fn;
return fn({
getState: getState,
action: action,
dispatch: dispatch
}, fn.length > 1 && decrementPendingCount(dispatch));
});
} catch (e) {
console.error(e); // eslint-disable-line no-console
}
return result;
};
};
};
return {
getListeners: getListeners,
isPending: isPending,
addListener: addListener,
addListeners: addListeners,
removeListeners: removeListeners,
decrementPendingCount: decrementPendingCount,
middleware: middleware
};
};