Created
March 12, 2012 20:05
-
-
Save bhang/2024367 to your computer and use it in GitHub Desktop.
KinveyCollection
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
// 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(); | |
/// ... |
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
I know this is a bit of a contrived example, but would you be able to use
$.ajaxSetup()
and eliminate the use of specifyingsync: authenticatedKinveySync
? gist