Skip to content

Instantly share code, notes, and snippets.

@bhang
Created March 12, 2012 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bhang/2024367 to your computer and use it in GitHub Desktop.
Save bhang/2024367 to your computer and use it in GitHub Desktop.
KinveyCollection
// Credentials for use with Kinvey
// NOTE: This example shows passing in the master secret.
// In a production environment, these credentials should be protected i.e.
// they should be requested from the user or secured via a login screen
var kinvey_app_key = 'kidxxxx';
var kinvey_secret = 'master secret';
// Modified sync to add authorization header for use with Kinvey
var authenticatedKinveySync = function(method, model, options) {
options.beforeSend = function(jqXHR) {
jqXHR.setRequestHeader(
'Authorization',
'Basic ' + $.base64.encode(
kinvey_app_key + ':' + kinvey_secret
)
);
}
// Call the default Backbone sync implementation
Backbone.sync.call(this, method, model, options);
}
// User submission model
var UserSubmissionModel = Backbone.Model.extend({
// Backbone looks for 'id' by default
// However, MongoDB uses '_id' so we need to override it
idAttribute: '_id',
// Use our modified version of sync to connect to Kinvey
sync: authenticatedKinveySync
});
// An example of a Kinvey collection that we want to interact with
var UserSubmissionsCollection = Backbone.Collection.extend({
model: UserSubmissionModel,
// Use our modified version of sync to connect to Kinvey
sync: authenticatedKinveySync,
// URL is a function of the app_key and the name of the collection
url: function() {
return 'https://baas.kinvey.com/appdata/' + kinvey_app_key + '/user_submissions/';
}
});
// Create an instance of our collection...
var UserSubmissions = new UserSubmissionsCollection();
// ... and fetch some data !!!
UserSubmissions.fetch();
/// ...
@dericcrago
Copy link

I know this is a bit of a contrived example, but would you be able to use $.ajaxSetup() and eliminate the use of specifying sync: authenticatedKinveySync? gist

@bhang
Copy link
Author

bhang commented Mar 15, 2012

Absolutely ! I debated long and hard over using that approach but excluded it in the end as I thought it might cause some confusion.

Another reason why I thought it best to leave it out was that using $.ajaxSetup in this way affects all AJAX requests, and the app may need to make calls to other services. Good catch though, and I'll be sure to mention it in my follow-up post, thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment