Created
September 21, 2011 14:39
-
-
Save zenlor/1232219 to your computer and use it in GitHub Desktop.
Backbone.js Sync method for reqwest.js and Ender.js
This file contains 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
(function (reqwest, Backbone) { | |
var methodMap, getUrl; | |
methodMap = { | |
'create': 'POST', | |
'update': 'PUT', | |
'delete': 'DELETE', | |
'read' : 'GET' | |
}; | |
getUrl = function(object) { | |
if (!(object && object.url)) return null; | |
return _.isFunction(object.url) ? object.url() : object.url; | |
}; | |
// Override `Backbone.sync` to use the lightweight [reqwest](https://github.com/ded/reqwest) ajax library | |
// does *not* supports `Backbone.emulateHTTP` and `Backbone.emulateJSON` | |
Backbone.sync = function(method, model, options, error) { | |
var params; | |
params = { | |
type: 'json', | |
method: methodMap[method], | |
headers: { 'Content-Type': 'application/json' }, | |
success: options.success, | |
error: options.error, | |
url: options.url? options.url : getUrl(model) | |
}; | |
if (params.method !== 'GET' && params.method !== 'DELETE') | |
params.data= JSON.stringify( options.data || model.toJSON()); | |
console.log(params) | |
return reqwest(params); | |
}; | |
})( window.reqwest || window.$.ajax, | |
window.Backbone || window.$.Backbone); // ender wraps libraries |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Like this, took me about 5 minutes to add it in and replace jQuery.