Skip to content

Instantly share code, notes, and snippets.

@wcjohnson
Created March 11, 2016 17:44
Show Gist options
  • Save wcjohnson/c84f0133971adb28f163 to your computer and use it in GitHub Desktop.
Save wcjohnson/c84f0133971adb28f163 to your computer and use it in GitHub Desktop.
observeSelector pattern
#
# Observable pattern for Redux selectors.
# Compares using _ deep equality.
# See: https://github.com/rackt/redux/issues/303#issuecomment-125184409
#
_ = require 'underscore'
deepEqualityTest = _.isEqual
objectEqualityTest = (a,b) -> a is b
observeSelector = (store, selector, onChange, observeInitialValue = true, equalityTest = deepEqualityTest) ->
lastState = undefined
watcher = ->
nextState = selector(store.getState())
if not equalityTest(nextState, lastState)
lastState = nextState
onChange(nextState)
unsubscriber = store.subscribe(watcher)
if observeInitialValue then watcher()
unsubscriber
stopObserving = (unsubscriber) -> unsubscriber()
module.exports = { observeSelector, stopObserving }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment