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

Overriding the Backbone.sync() method


Backbone provides a single gateway for all its data communication. All the data requests are sent via the sync() method that gets called whenever any CRUD operation is processed. This sync() method does a number of jobs, such as setting the URL, parameters and content type, and mimicking HTTP requests for old browsers that do not support PUT and DELETE requests. Whenever we call a fetch() or save() method on a model or collection, the sync() method is executed.

But when do we need to override this method? Sometimes, you may need a separate implementation of the REST API method, which Backbone does not provide. This can be for a certain model or collection, or the implementation can persist for the complete project. This is how the method map is written in Backbone by default:

var methodMap = {
  'create': 'POST',
  'update': 'PUT',
  'patch': 'PATCH',
  'delete': 'DELETE',
  'read': 'GET'
};

Now, you may have a particular model or collection that will listen...