Chapter 3. Accessing Server Data with Models

In this chapter, you'll learn how to:

  • Use Model, Backbone's main class to work with data
  • Create new Model subclasses
  • Get and set Model attributes and trigger other code when these attributes change
  • Store these attributes to a remote server and retrieve them from the server
  • Use the several convenience methods that Model has borrowed from Underscore

The purpose of Models

Models in Backbone are the core of all data interactions, both within the client code itself and when communicating with a remote server. While one can simply use a plain JavaScript object instead of a Model, Models offer three major advantages:

  • Models use Backbone's class system, making it easy to define methods, create subclasses, and so on
  • Models allow other code to listen for and respond to changes in the Model attributes
  • Models simplify and encapsulate the logic used to communicate with the server

As discussed in the previous chapter, we can create our own subclass of Model using extend:

var Cat = Backbone.Model.extend({
     // The properties and methods of our "Cat" class would go here
});

Once we've created that class, we can instantiate new Model instances using JavaScript's new keyword, and (optionally) we can pass in an initial set of attributes and options, as follows:

var garfield = new Cat({
    name: 'Garfield',
    owner: 'John'
}, {
    estimateWeight: true
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.167.170