Book Image

Backbone.js Patterns and Best Practices

By : Swarnendu De
Book Image

Backbone.js Patterns and Best Practices

By: Swarnendu De

Overview of this book

Table of Contents (19 chapters)
Backbone.js Patterns and Best Practices
About the Author
About the Reviewers
Precompiling Templates on the Server Side

Understanding the collection of multiple model types

There are cases when we have a mixed set of data coming from the server and we need to put the complete data in a single collection. For example, assume that the server is sending the complete employee details of a company. Now, there are different types of employees—developers, managers, designers, and so on, and you want to have different model types for each of these. How is the collection supposed to hold all types of models together? Here is an example with which you can get the desired functionality:

var Employee = Backbone.Model.extend();
var Developer = Employee.extend();
var Manager = Employee.extend();

var Employees = Backbone.Collection.extend({
  url: 'employees.json',
  model: function (attrs, options) {
    // For each data, check the attribute type
    switch (attrs.type) {
      case "Developer":
        return new Developer(attrs, options);

      case "Manager":
        return new Manager(attrs, options...