Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

BaseModel

Matt Sweetman edited this page · 1 revision

BaseModel

BaseModel is a subclass of Backbone.Model that helps you manage nested data structures.

Nested models

BaseModel allows you to define a submodels hash that maps data properties to their relevant classes. When the model fetches and parses JSON data it will automatically instantiate the mapped model class and give it the nested object.

The following example shows you the JSON data and the corresponding model configuration:

// Object representing a 'car' model, to be fetched from the server
{
  model: 'Volkswagen',
  engine: {
    capacity: 3.5,
    cylinders: 6
  },
  paintColors: [
    {name: 'Brilliant White', value: '#FFFFFF'},
    {name: 'Brick Red', value: '#FF0000'}
  ]
}
// Configure the nested model and collection classes
var PaintModel = BaseModel.extend({
  defaults: {
    name: 'Black',
    value: '#000000'
  }
});

var PaintCollection = Backbone.Collection.extend({
  model: PaintModel
});

var EngineModel = BaseModel.extend({
  defaults: {
    capacity: 0,
    cylinders: 0
  }
});

var CarModel = BaseModel.extend({
  // A map of property names in the JSON data and the corresponding classes to be created
  submodels: {
    engine: EngineModel,
    paintColors: PaintCollection
  }
});

The submodel map is only used when the model parses data - this occurs whenever the model fetches data from the server using fetch(), or the parse option is given to set().

var car = new CarModel();

// Submodels will be automatically created when the JSON data is fetched and parsed
car.fetch();

// Submodels will also be created if parse:true is used in the set function
car.set(carJSONData, {parse:true});

Using toJSON() with nested models

By default toJSON() only JSONifies the data from the current model it's called on. Nested models will still be references back to the BaseModel instances. In order to completely JSONify the nested model structure you must pass deep:true to the toJSON function:

car.toJSON({deep:true}) // Recursively calls toJSON on nested models

Note: This will only work on subclasses of BaseModel. If any of the models in your hierarchy don't inherit from BaseModel it will break the recursive call.

Additional note: This can be slow on extremely large and deeply nested data sets.

Custom data serialization

Occasionally it can be useful to separate the data used to render templates from the data sent to the server during a CRUD operation.

Typically templates are rendered using the object returned from toJSON(). However the same function is used internally by Backbone when preparing the data for CRUD. If you're working with a non-standard RESTful API you might need to prepare a different representation of your data for synchronization with the server.

To do this just create a serialize function in your model class and return a JSON string of the data you want synced to the server. The serialize function is automatically called just before a create, update or patch ajax call:

CarModel = BaseModel.extend({
  serialize: function() {
    // Called just before a CRUD operation. Must return a JSON string.
    return JSON.stringify({
      model: this.attributes.model,
      engine: '6,3.5', // Modify how the engine data is represented
    });
  }
});
Something went wrong with that request. Please try again.