Created
November 10, 2012 06:55
-
-
Save fourcolors/4050235 to your computer and use it in GitHub Desktop.
Backbone model override
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
# 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