mobx autorun code example
Example 1: mobx listen to changes
import { observable, observe } from "mobx"
const person = observable({
firstName: "Maarten",
lastName: "Luther"
})
const disposer = observe(person, change => {
console.log(change.type, change.name, "from", change.oldValue, "to", change.object[change.name])
})
person.firstName = "Martin"
disposer()
const disposer2 = observe(person, "lastName", change => {
console.log("LastName changed to ", change.newValue)
})
Example 2: mobx listen to changes
const theme = observable({
backgroundColor: "#ffffff"
})
const disposer = intercept(theme, "backgroundColor", change => {
if (!change.newValue) {
return null
}
if (change.newValue.length === 6) {
change.newValue = "#" + change.newValue
return change
}
if (change.newValue.length === 7) {
return change
}
if (change.newValue.length > 10) disposer()
throw new Error("This doesn't like a color at all: " + change.newValue)
})