Docs

Everything You Need to Know

Models

Use

Models provide a powerful interface to your data to make your work easier. When using plain JavaScript objects, you can not judge easily when the data changes. In contrast, models automatically render their bound views when you modify their data.

Models are easy to create. Just use the $.Model() method and pass it the data to encapsulate. In the following example we 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);

// 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. Since it is now a model, we can access its data with accessor methods. These are:

  • personModel.getItemProp()
  • personModel.setItemProp()
  • personModel.deleteItemProp()

To get the name, we would do this:

personModel.getItemProp('name')
// returns: {first: "John", last: "Doe"}
// To get the first name and last name separate:
var firstName = personModel.getItemProp('name').first
// returns: "John"
var lastName = personModel.getItemProp('name').last
// returns: "Doe"

Now let's create a model that holds an array of objects. This is the same as the previous example:

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);
fruits = undefined;

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

Because this model holds an array, we need to provide an index to indicate where in the array we want to get the property from. Theis is, of course, 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. Models are ideal when you want your views to update automatically when the data changes.

ChocolateChip-UI tries to be efficient at rendering model changes. However, if you are pushing the envelope with data sizes and rapid changes and you see a serious performance degradation, try rendering your view with raw JavaScript data. You can always store the data in a model after you are finished manipulating your data.