Skip to content

Instantly share code, notes, and snippets.

@nervetattoo
Created December 14, 2012 18:42
Show Gist options
  • Save nervetattoo/4287589 to your computer and use it in GitHub Desktop.
Save nervetattoo/4287589 to your computer and use it in GitHub Desktop.
Filtered backbone.sync
var handleUserLoggedOut = function(response, type, xhr) {
var def = $.Deferred();
if (resp.error === 'some error about ') {
// Here we render a view for the user to log back in and track failed requests to re-apply them later
return def.reject(resp.error);
}
return def.resolve(resp);
}
Backbone._sync = Backbone.sync;
Backbone.sync = function(method, model, options) {
// CSRF token
var formToken = config.formtoken;
if (method !== 'read' && formToken) {
options.data = options.data || ({});
_.defaults(options.data, {
csrf_token : formToken
});
}
// Get reference to xhr object by first doing the sync method
var xhr = Backbone._sync(method, model, options);
// Pipe through the logged out detector, this will return a $.Deferred, not the jquery xhr superset
var def = xhr.pipe(handleUserLoggedOut, handleServerErrors);
// Merge the xhr object back into the Deferred and return it
return _.extend(def, xhr);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment