Created
October 30, 2017 10:14
-
-
Save Deathspike/8abe9658e35b6cb95c74eb7a892b8ac8 to your computer and use it in GitHub Desktop.
mobx deep observe
This file contains 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
import * as mobx from 'mobx'; | |
export function deepObserve(onChange: () => void, value: any) { | |
if (value && typeof value === 'object') { | |
mobx.observe(value, (change: any) => { | |
onChange(); | |
if (change.added) { | |
change.added.forEach(deepObserve.bind(null, onChange)); | |
} else if (change.newValue) { | |
deepObserve(onChange, change.newValue); | |
} | |
}); | |
if (Array.isArray(value) || mobx.isObservableArray(value)) { | |
value.forEach(deepObserve.bind(null, onChange)); | |
} else { | |
Object.keys(value).map(x => value[x]).forEach(deepObserve.bind(null, onChange)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment