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...