-
Notifications
You must be signed in to change notification settings - Fork 173
Usage with Backbone.js
jeff-h edited this page Nov 5, 2015
·
5 revisions
For a full example app which uses Backbone.Marionette to connect to a RESTful Drupal instance, check out todo_restful.
RESTful.module responses contain a data
element, which contains the model data. Backbone.js by default assumes the entire response will be the model data, so your models and collections will need to implement the parse()
method, to give Backbone just the response's data
element.
{
"data": [
{
"id": "5",
"label": "Barry",
"self": "http://drupalsite.local/api/v1.1/users/5",
"mail": "[email protected]"
}
],
"self": {
"title": "Self",
"href": "http://drupalsite.local/api/v1.1/users/5"
}
}
var User = Backbone.Model.extend({
urlRoot : function() {
return restBasePath + '/api/users/';
},
// Modify the response that RESTful.module gives us.
parse: function(response, options) {
if (response.data) {
// RESTful sends models buried inside a data element.
return response.data[0];
}
return response;
},
});
var Users = Backbone.Collection.extend({
model: User,
url : restBasePath + '/api/users/',
// RESTful sends models buried inside a data element.
parse: function(response) {
return response.data;
},
});
You'll need to add headers to every request that needs to be authenticated. When using cookie auth, you'll want to add the X-CSRF-Token
and when using token auth you'll need to add the access_token
.
This can neatly be achieved in Backbone using underscore's _.wrap
method. For example:
// Make all our AJAX requests send the access_token in a header.
self.addAuthHeaders({
'X-CSRF-Token': self.get("X-CSRF-Token")
});
or
// Make all our AJAX requests send the access_token in a header.
self.addAuthHeaders({
'access_token': self.get("access_token")
});
and
addAuthHeaders: function(authHeaders) {
Backbone.ajax = _.wrap(Backbone.ajax, function(originalFunc, params) {
params.headers = _.extend({}, params.headers, authHeaders);
return originalFunc(params);
});
}