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

Serializing models


So far, the model data we used in our examples in the previous chapters are all simple data objects with attributes. However, there might be a case where the server is sending a different data format and you need to extract the essential part from it and apply it to the related model. For example, consider the following data:

{
  "name": "John Doe",
  "email": "[email protected]"
}

Instead of sending the preceding data, the server returns the following data:

{
  "user": {
    "name": "John Doe",
    "email": "[email protected]"
  }
}

This data cannot be applied directly to a model with the attributes name and email. If we call the fetch() method on the model now, it will just add another attribute named user to the model. The method that can help us overcome this issue is called parse(). By default, this method just passes the server response and the model applies whatever it receives from the parse() method. Here is how it is defined in Backbone.js:

parse: function (resp...