Skip to content

Instantly share code, notes, and snippets.

@hamedb89
Last active August 29, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamedb89/14018d1cc80916145ecf to your computer and use it in GitHub Desktop.
Save hamedb89/14018d1cc80916145ecf to your computer and use it in GitHub Desktop.
Backbone.sync coffeescript
_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