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
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Precompiling Templates on the Server Side
Index

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);
        break;

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