Skip to content

Instantly share code, notes, and snippets.

@fourcolors
Created November 10, 2012 06:55
Show Gist options
  • Save fourcolors/4050235 to your computer and use it in GitHub Desktop.
Save fourcolors/4050235 to your computer and use it in GitHub Desktop.
Backbone model override
# Method Summary
# Before a request gets sent out we need to make sure
# it's formatted correctly and contains the right
# info. We are adding the CSRF tokens in the header
# so our POST request work and making sure any
# namespaced attributes are working so the server is
# happy. If we are using other AJAX request to post
# date we will have to add something for jQuery.
preProcessSync: ->
# Fix backbone headers
Backbone._sync = Backbone.sync
Backbone.sync = (method, model, options) ->
# Add CSRF token to request header
token = window.ENV.AUTHENTICITY_TOKEN
new_options = _.extend
beforeSend: (xhr, settings) ->
if token and method != 'GET' # Get request don't need CSRF token
xhr.setRequestHeader('X-CSRF-Token', token)
, options
# API namespace puts this object under
# a namespace of this name.
# This should the same name as the class name.
# Namespace attributes being sent by the models
# api_namespace attribute if it's set
if model.api_namespace
namespaced_attributes = {}
namespaced_attributes[model.api_namespace] = model.attributes
model.attributes = namespaced_attributes
return Backbone._sync(method, model, new_options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment