Last active
August 29, 2015 14:24
-
-
Save hamedb89/14018d1cc80916145ecf to your computer and use it in GitHub Desktop.
Backbone.sync coffeescript
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
_sync = Backbone.sync | |
methodMap = | |
'create': 'POST' | |
'update': 'PUT' | |
'patch': 'PATCH' | |
'delete': 'DELETE' | |
'read': 'GET' | |
Backbone.sync = -> | |
type = methodMap[method] | |
# Default options unless specified | |
_.defaults options or (options = {}), | |
emulateHTTP: Backbone.emulateHTTP | |
emulateJSON: Backbone.emulateJSON | |
params = type: type, dataType: 'json' | |
unless options.url then params.url = _.result model, 'url' or urlError() | |
if options.data is null and model? and method in ['create', 'update', 'patch'] | |
params.contentType = 'application/json' | |
params.data = JSON.stringify options.attrs or model.toJSON options | |
if options.emulateJSON | |
params.contentType = 'application/x-www-form-urlencoded' | |
params.data = if params.data then model: params.data else {} | |
if options.emulateHTTP and type in ['PUT', 'DELETE', 'PATCH'] | |
params.type = 'POST' | |
if options.emulateJSON then params.data._method = type | |
beforeSend = options.beforeSend | |
options.beforeSend = (xhr) -> | |
xhr.setRequestHeader 'X-HTTP-Method-Override', type | |
if beforeSend then return beforeSend.apply this, arguments | |
unless params.type is 'GET' and options.emulateJSON then params.processData = false | |
error = options.error | |
options.error = (xhr, textStatus, errorThrown) -> | |
options.textStatus = textStatus | |
options.errorThrown = errorThrown | |
if error then error.call options.context, xhr, textStatus, errorThrown | |
xhr = options.xhr = Backbone.ajax _.extend params, options | |
model.trigger 'request', model, xhr, options | |
xhr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment