Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions src/createStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,17 @@ export default function createStore(reducer, preloadedState, enhancer) {
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
function subscribe(listener, filter) {
if (typeof listener !== 'function') {
throw new Error('Expected the listener to be a function.')
}

if (typeof filter !== 'function') {
filter = filter === true ? pure_filter : false
}

const nextListener = { listener, filter }

if (isDispatching) {
throw new Error(
'You may not call store.subscribe() while the reducer is executing. ' +
Expand All @@ -115,7 +121,7 @@ export default function createStore(reducer, preloadedState, enhancer) {
let isSubscribed = true

ensureCanMutateNextListeners()
nextListeners.push(listener)
nextListeners.push(nextListener)

return function unsubscribe() {
if (!isSubscribed) {
Expand All @@ -132,11 +138,15 @@ export default function createStore(reducer, preloadedState, enhancer) {
isSubscribed = false

ensureCanMutateNextListeners()
const index = nextListeners.indexOf(listener)
const index = nextListeners.indexOf(nextListener)
nextListeners.splice(index, 1)
}
}

function pure_filter(oldState, newState) {
return oldState === newState
}

/**
* Dispatches an action. It is the only way to trigger a state change.
*
Expand Down Expand Up @@ -181,6 +191,8 @@ export default function createStore(reducer, preloadedState, enhancer) {
throw new Error('Reducers may not dispatch actions.')
}

const oldState = currentState

try {
isDispatching = true
currentState = currentReducer(currentState, action)
Expand All @@ -190,8 +202,11 @@ export default function createStore(reducer, preloadedState, enhancer) {

const listeners = (currentListeners = nextListeners)
for (let i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
const { listener, filter } = listeners[i]
const apply_filter = filter && filter(oldState, currentState)
if (!apply_filter) {
listener()
}
}

return action
Expand Down