mobx listen to changes

Solutions on MaxInterview for mobx listen to changes by the best coders in the world

showing results for - "mobx listen to changes"
Vicente
09 Jan 2021
1import { observable, observe } from "mobx"
2
3const person = observable({
4    firstName: "Maarten",
5    lastName: "Luther"
6})
7
8const disposer = observe(person, change => {
9    console.log(change.type, change.name, "from", change.oldValue, "to", change.object[change.name])
10})
11
12person.firstName = "Martin"
13// Prints: 'update firstName from Maarten to Martin'
14
15disposer()
16// Ignore any future updates
17
18// observe a single field
19const disposer2 = observe(person, "lastName", change => {
20    console.log("LastName changed to ", change.newValue)
21})
22
Emy
21 Jan 2017
1const theme = observable({
2    backgroundColor: "#ffffff"
3})
4
5const disposer = intercept(theme, "backgroundColor", change => {
6    if (!change.newValue) {
7        // ignore attempts to unset the background color
8        return null
9    }
10    if (change.newValue.length === 6) {
11        // correct missing '#' prefix
12        change.newValue = "#" + change.newValue
13        return change
14    }
15    if (change.newValue.length === 7) {
16        // this must be a properly formatted color code!
17        return change
18    }
19    if (change.newValue.length > 10) disposer() // stop intercepting future changes
20    throw new Error("This doesn't like a color at all: " + change.newValue)
21})
22