Skip to content

Instantly share code, notes, and snippets.

@giiska
Created July 7, 2014 06:19
Show Gist options
  • Save giiska/249fb9df5af6e87abd85 to your computer and use it in GitHub Desktop.
Save giiska/249fb9df5af6e87abd85 to your computer and use it in GitHub Desktop.
Using custom headers with Backbone.sync backbone restful token
/*
* Using AMD/RequireJS
*
* The `auth` module handles OAuth and stores the
* access token that needs to be sent in a header
*/
define(['api/auth'], function (auth) {
'use strict';
/*
* Store a version of Backbone.sync to call from the
* modified version we create
*/
var backboneSync = Backbone.sync;
Backbone.sync = function (method, model, options) {
/*
* The jQuery `ajax` method includes a 'headers' option
* which lets you set any headers you like
*/
options.headers = {
/*
* Set the 'Authorization' header and get the access
* token from the `auth` module
*/
'Authorization': 'Bearer ' + auth.getAccessToken()
};
/*
* Call the stored original Backbone.sync method with
* extra headers argument added
*/
backboneSync(method, model, options);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment