Created
January 7, 2014 17:39
-
-
Save dylants/8303201 to your computer and use it in GitHub Desktop.
A Backbone Model which provides a hook to handle unauthorized API requests to the server. When dealing with server side security, this is one way of handling an unauthorized user on the client side in a generic way. By extending this model rather than Backbone's model, you can decide what should happen to the user when they hit an unauthorized r…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* global define:true */ | |
define([ | |
"backbone" | |
], function(Backbone) { | |
"use strict"; | |
// Extend Backbone's Model to override the sync function. Doing so allows us | |
// to get a hook into how the errors are handled. Here we can check if the | |
// response code is unauthorized, and if so, navigate to the login page | |
return Backbone.Model.extend({ | |
sync: function(method, model, options) { | |
wrapBackboneError(options); | |
Backbone.Model.prototype.sync.apply(this, arguments); | |
} | |
}); | |
}); | |
/** | |
* Wrap Backbone's error with our own, which handles unauthenticated response codes | |
* and performs the necessary logic in this case (navigate to login page, perhaps) | |
* | |
* @param {Object} options The options for the sync function | |
*/ | |
var wrapBackboneError = function(options) { | |
var error = options.error; | |
options.error = function(response) { | |
if (response.status === 401) { | |
console.log("navigate to login!"); | |
} else { | |
if (error) error(response); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment