Mobx computed example

Shows mobx's computed value feature and how it caches it's value 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://unpkg.com/[email protected]/lib/mobx.umd.min.js"></script>
<script src="https://unpkg.com/[email protected]/index.js"></script>
<script src="https://rawgit.com/mattruby/mobx-examples/master/logging-utils.js"></script>
<!--<script src="../logging-utils.js"></script>-->
<script>
	wrapConsole();
</script>
<!--<script src="demo.js"></script>-->

JavaScript

var person = mobx.observable({
	firstName: 'Matt',
	lastName: 'Ruby',
	age: 0,
	get fullName () {
		// Note how this computed value is cached.
		// We only hit this function 3 times.
		console.log('hit fullName');
		return mobx.untracked(function(){return person.firstName}) + ' ' + this.lastName;
	}
});

mobx.autorun(function auto_fullNameAge () {
	console.log('autorun: ' + person.fullName + ' ' + person.age);
});

// this will print Matt Ruby NN 10 times
_.times(10, function () {
	person.age = _.random(40);
});

person.firstName = 'Mike';
person.firstName = 'Lissy';