diff --git a/src/createStore.js b/src/createStore.js index 53a2b9dbf5..3616cf45cf 100644 --- a/src/createStore.js +++ b/src/createStore.js @@ -55,9 +55,16 @@ export default function createStore(reducer, initialState, enhancer) { var currentReducer = reducer var currentState = initialState - var listeners = [] + var currentListeners = [] + var nextListeners = currentListeners var isDispatching = false + function beforeMutatingListeners() { + if (nextListeners === currentListeners) { + nextListeners = currentListeners.slice() + } + } + /** * Reads the state tree managed by the store. * @@ -95,17 +102,21 @@ export default function createStore(reducer, initialState, enhancer) { throw new Error('Expected listener to be a function.') } - listeners.push(listener) var isSubscribed = true + beforeMutatingListeners() + nextListeners.push(listener) + return function unsubscribe() { if (!isSubscribed) { return } isSubscribed = false - var index = listeners.indexOf(listener) - listeners.splice(index, 1) + + beforeMutatingListeners() + var index = nextListeners.indexOf(listener) + nextListeners.splice(index, 1) } } @@ -160,9 +171,9 @@ export default function createStore(reducer, initialState, enhancer) { isDispatching = false } - var currentListeners = listeners.slice() - for (var i = 0; i < currentListeners.length; i++) { - currentListeners[i]() + var listeners = currentListeners = nextListeners + for (var i = 0; i < listeners.length; i++) { + listeners[i]() } return action