Skip to content

Instantly share code, notes, and snippets.

@mrjjwright
Created October 28, 2010 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mrjjwright/652546 to your computer and use it in GitHub Desktop.
Save mrjjwright/652546 to your computer and use it in GitHub Desktop.
plugin for Backbone that send the models as application/json encoded bodies
methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
getUrl = function(object) {
if (!(object && object.url)) {
throw new Error("A 'url' property or function must be specified");
} else {
return _.isFunction(object.url) ? object.url() : object.url;
}
};
return (Backbone.sync = function(method, model, success, error) {
var data, sendModel, type;
type = methodMap[method];
sendModel = method === "create" || method === "update";
data = sendModel ? JSON.stringify(model) : {};
if (Backbone.emulateHttp && (type === 'PUT' || type === 'DELETE')) {
data._method = type;
type = 'POST';
}
return $.ajax({
url: getUrl(model),
type: type,
contentType: "application/json",
processData: false,
data: data,
dataType: 'json',
success: success,
error: error
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment