Skip to content

Instantly share code, notes, and snippets.

@salbito
Forked from powmedia/gist:1081802
Created August 23, 2011 13:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save salbito/1165174 to your computer and use it in GitHub Desktop.
Save salbito/1165174 to your computer and use it in GitHub Desktop.
Backbone.sync for Titanium
//Customise Backbone.sync to work with Titanium rather than jQuery
Backbone.sync = (function() {
var methodMap = {
'create': 'POST',
'read' : 'GET',
'update': 'PUT',
'delete': 'DELETE'
};
var xhr = Ti.Network.createHTTPClient({ timeout: 5000 });
return function(method, model, options) {
var type = methodMap[method],
params = _.extend({}, options);
//==== Start standard Backbone.sync code ====
// Ensure that we have a URL
if (!params.url) params.url = getUrl(model) || urlError();
// Ensure that we have the appropriate request data.
if (!params.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.processData = true;
params.data = params.data ? {model : params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
//==== End standard Backbone.sync code ====
//Handle success
xhr.onload = function() {
params.success(JSON.parse(this.responseText));
};
//Handle error
xhr.onerror = params.error;
//Prepare the request
xhr.open(type, params.url);
//Add request headers etc.
xhr.setRequestHeader('Content-Type', params.contentType);
if (params.beforeSend) params.beforeSend(xhr);
//Make the request
xhr.send(params.data);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment