Cover by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Model

JavaScriptMVC’s model and its associated plug-ins provide lots of tools around organizing model data, such as validations, associations, lists, and more. But the core functionality is centered around service encapsulation, type conversion, and events.

Attributes and Observables

Of absolute importance to a model layer is the ability to get and set properties on the modeled data, and to listen for changes on a model instance. This is the Observer pattern, and it lies at the heart of the MVC approach—views listen to changes in the model.

Fortunately, with JavaScriptMVC, it is easy to make any data observable. A great example is pagination. It’s very common for multiple pagination controls to exist on the page. For example, one control might provide Next and Previous page buttons; another control might detail the items the current page is viewing (e.g., “Showing items 1-20”). All pagination controls need the exact same data:

offset

The index of the first item to display

limit

The number of items to display

count

The total number of items

We can model this data with JavaScriptMVC’s $.Model:

var paginate = new $.Model({
  offset: 0,
  limit: 20,
  count: 200
});

The paginate variable is now observable. We can pass it to pagination controls that can read from, write to, and listen for property changes. You can read properties like normal or by using the model.attr(NAME) method:

assertEqual( paginate.offset, 0 );
assertEqual( paginate.attr('limit') , 20 );

If we click the next button, we need to increment ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required