Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jspillers
Forked from jumski/backbone_sync_hack.coffee
Created December 2, 2011 00:17
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 jspillers/1420911 to your computer and use it in GitHub Desktop.
Save jspillers/1420911 to your computer and use it in GitHub Desktop.
BackboneJS sync hack to namespace params when saving/updating model
###
Usage:
* add model.name property that will be used as a namespace in the json request
* put this code before your Backbone app code
* use toJSON() as usual (so there is no namespacing in your templates)
* your model's data will be sent under model.name key when calling save()
###
# save reference to Backbone.sync
Backbone.oldSync = Backbone.sync
# override original method
Backbone.sync = (method, model, options) ->
# save reference to original toJSON()
model.oldToJSON = model.toJSON
# override this model instance toJSON() method
model.toJSON = ->
json = {}
# namespace original json values under model.name key
json[model.name] = @oldToJSON()
json
# call original sync method
syncReturnValue = Backbone.oldSync method, model, options
# restore original toJSON() on this model instance
model.toJSON = model.oldToJSON
delete model.oldToJSON
# return value returned by original sync
syncReturnValue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment