javascript - How to override Backbone.sync?




backbone.js (2)

I'm trying out Backbone.js, and one of the things I'm trying is to make a call to a remote API, so I need to be able to override Backbone.sync, as I understand the documentation.

There isn't an example of how to do that in the documentation itself, and there doesn't appear to be a google group for Backbone... can someone point out an example for doing this?


I know this answer is a bit too late, and the answer from @Raynos is great, but I did it a bit differently, and maybe it would be useful for you or for any other person trying to use an API with Backbone.

Instead of overriding Backbone.sync, I overrided Backbone.ajax, because it's where the ajax request is made.

Here's an example :

// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
Backbone.ajax = function() {
    var args = Array.prototype.slice.call(arguments, 0);

    // Here, I add the OAuth token (or any other token)
    // But before, I check that data exists, if not I add it
    if (args[0]['data'] === undefined) {
        args[0]['data'] = {};
    }
    args[0]['data']['token'] = 'any_api_token_here';

    return Backbone.$.ajax.apply(Backbone.$, args);
};

I typically need to override backbone's sync method when I need to only sync certain attributes. A typical implementation looks like this:

sync: function (method, model, options) {
  options.data = _.pick(this.attributes, 'foo', 'bar', 'baz');
  return Backbone.sync.call(this, method, model, options);
}






backbone.js