Created
March 11, 2016 17:44
-
-
Save wcjohnson/c84f0133971adb28f163 to your computer and use it in GitHub Desktop.
observeSelector pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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