Docs

Everything You Need to Know

Models

Use

Truck Tank

Models provide a powerful interface to your data so that Truck can do things to make your work easier. Although many frameworks don't use models but expect you to use plain JavaScript objects, this have a number of drawbacks. You can not judge easily when the state of the data changes without costly polling and caching of duplicates, etc.

Model are easy to create. Just use the $.Model method to do so. We'll first create a model that represents a JavaScript object of key/value pairs:

// Plain JavaScript object:
var myObject = {
  name: {
    first: 'John',
    last: 'Doe'
  },
  age: 32,
  job: 'web developer'
}

// Create a model:
var PersonModel = $.Model(myObject, 'person-model');

// Get rid of the plain JavaScript object,
// since we don't need it any more:
myOjbect = undefined;
          

To initialize the model, we gave it the object to use and a handle, which is a name Truck can use to identify the model. And that's it. Since it is now a model, we can access the model with object appropriate methods. These are:

  • PersonModel.getItemProp()
  • PersonModel.setItemProp()
  • PersonModel.deleteItemProp()

In our case, if we want to get the name, we might do this:

PersonModel.getItemProp('name')
// returns: {first: "John", last: "Doe"}
// To get the first name and last name separate:
PersonModel.getItemProp('name').first
// returns: "John"
PersonModel.getItemProp('name').last
// returns: "Doe"
          

Now let's create a model that holds a collection. By collection we mean an array. This might be a simple array or an array of objects. Making it is the same as we did for the simple object:

var fruits = [
  {name: "Apple", image: 'images/apple.png'},
  {name: "Banana", image: 'images/banana.png'},
  {name: "Orange", image: 'images/orange.png'},
  {name: "Mango", image: 'images/mango.png'} 
];
var FruitModel = $.Model(fruits, 'fruit-model');
fruits = undefined;

fruits.getItemProp(2, 'name'); // returns "Orange"
// Returns

In the above example, we accessed the data a little differently. Because this is a collection, we need to tell Truck what index of the collect we want to get the property from. The index, like arrays, is zero-based.

When Not To Use

Not all data needs to be in a model. If you have simple data, a string, an array of a couple of items, or a very simple object, it doesn't make sense to put them in a model. Similarly, if your data is of a temporary nature, don't bother putting it in a model. If your data is complex and your app depends on it for functionality, put it in a model. However, if you have some data that needs to be manipulated in very rapid operations, leave it as raw data. You'll have better performance. When you're done manipulating the data, you can store it in a model. Models are ideal when you want to bind a view to one, or persist its data in a local data store automatically.