Skip to content

Instantly share code, notes, and snippets.

@Deathspike
Created October 30, 2017 10:14
Show Gist options
  • Save Deathspike/8abe9658e35b6cb95c74eb7a892b8ac8 to your computer and use it in GitHub Desktop.
Save Deathspike/8abe9658e35b6cb95c74eb7a892b8ac8 to your computer and use it in GitHub Desktop.
mobx deep observe
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