Mobx transaction example
Shows mobx's transaction value feature and how it batches updates author(s): Matt Ruby
by Matt Ruby
HTML
<div id="react-log"></div>
<script src="https://cdn.jsdelivr.net/g/[email protected](react.min.js+react-dom.min.js),[email protected]"></script>
<script src="https://npmcdn.com/[email protected]/lib/mobx.umd.min.js"></script>
<script src="https://npmcdn.com/mobx-react"></script>
<script src="https://rawgit.com/mattruby/mobx-examples/master/logging-utils.js"></script>
<script>
wrapConsole();
</script>
JavaScript
var person = mobx.observable({
firstName: 'Matt',
lastName: 'Ruby',
age: 0,
fullName: function () {
return this.firstName + ' ' + this.lastName;
}
});
// you could also instantiate a Person and play with it's prototype.
_.assign(person, {
setFirstAndLastName: mobx.action(function setFirstAndLastName (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
})
});
mobx.autorun(function () {
console.log(person.fullName + ' ' + person.age);
});
// Note how we're changing 2 fields without using transaction.
// action wraps everything inside a transaction automatically
person.setFirstAndLastName('Jon', 'Smith');
// these will fire no problem as we're NOT in strict mode
person.firstName = 'Mike';
person.lastName = 'Peterson';