Milo Basics - Models
An introduction to milo Models.
by Jason Green
HTML
<script src="https://rawgit.com/milojs/milo/master/dist/milo.min.js"></script>
<!-- This lesson on milo models is all in the javascript below.
There is no HTML required. Milo models are just as useful in
the backend as they are in the front end. -->
<!-- You'll want to open your console to see the logs. -->
JavaScript
milo(function(){
// Let's create a new milo model, we'll expose it on the window so
// we can play around with it in the console. Just remember to set
// the frame (in chrome) to 'result(fiddle.jshell.net)'
var user = window.user = new milo.Model;
// Milo models allow us to safely access deeply nested properties
// without risk of errors. The model is used as a function and takes
// a string in the form of a property access path. When we do this,
// we get a model path.
var streetModelPath = user('.address.street');
// We can then retrieve and manipulate the data of the model with
// methods of the model path.
var street = streetModelPath.get();
// Note: ModelPath instances can be used just like models. This can
// be conveniente when dealing with complex data structures.
// Logs 'undefined' because we haven't set this data yet.
console.log('LOG 1: ', street);
// Unless you have specific use of the model path, you can just
// access these methods directly like this.
user('.address.street').set('Victoria Street');
// You can get the whole data object of the model simply by calling
// get on the model. This will console log a nested object.
console.log('LOG 2: ', user.get() );
// The string used in the model safe-access function can also take
// array syntax.
user('.friends[0]').set('Jason Green');
user('.friends[1]').set('Evgeny Pobereskin');
// We also have syntax for interpolation, simply pass a string with
// a $1 and then a second value.
console.log('LOG 3: ', user('.friends[$1]', 1).get());
// This is the same as the following
console.log('LOG 4: ', user('.friends[' + 1 + ']').get());
// Interpolation can be used for property names, and we can pass
// multiple values
console.log('LOG 5: ', user('.$1[$2]', 'friends', 0).get());
// We can delete values
...