Skip to content

Instantly share code, notes, and snippets.

@ch3stnut
Last active August 29, 2015 13:58
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 ch3stnut/10364526 to your computer and use it in GitHub Desktop.
Save ch3stnut/10364526 to your computer and use it in GitHub Desktop.
For BackboneRails series. Code that adds the CSRF token to CRUD requests automatically, merged with the original sync config file by BackboneRails.
do (Backbone) ->
Backbone._sync = Backbone.sync
Backbone.sync = (method, entity, options={}) ->
_.defaults options,
beforeSend: _.bind( methods.beforeSend, entity )
complete: _.bind( methods.complete, entity )
if method is 'create' or method is 'update' or method is 'put' or method is 'delete'
options.headers ?= {}
options.headers["X-CSRF-Token"] = $("meta[name='csrf-token']").attr 'content'
sync = Backbone._sync(method, entity, options)
if !entity._fetch and method is "read"
entity._fetch = sync
sync
methods =
beforeSend: ->
@trigger "sync:start", @
complete: ->
@trigger "sync:stop", @
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment