Say that I have a Collection and I've made changes to many of its Models. What's the best way to save all of the changes using a single HTTP request?
相关问题
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- Backbone.js PushState routes .htaccess only workin
- Include empty value fields in jQuery .serialize()
- Disable Browser onUnload on certain links?
Usually REST backends handle single instance creation/update. You would need to change that to accept an array of objects.
That said, on the client side, you would need to go directly to the Backbone.sync function
In this case your model should be an array of model. The method should be "create" or "save" and the options take the same type of options as a jQuery ajax call (error, success, etc.)
This code adds a new method to the collection prototype just to call the save method of those models that had changed. It worked for me:
Gist link: https://gist.github.com/julianitor/701c677279bac1529b88
You should extend
Backbone.Collection
, giving it asave()
method that would check each of its modelshasChanged()
.Then it should call
Backbone.sync
, which you'll probably have to extend a little into a custom sync function. If you do use a customBackbone.sync
function, then be sure to set it on your collection.A different approach (using a model to represent the collection) is here: "How" to save an entire collection in Backbone.js - Backbone.sync or jQuery.ajax?
I also like https://stackoverflow.com/a/7986982/137067
I'm going to do the Wrong Thing here and quote Wikipedia regarding proper RESTful practices: a PUT to
example.com/resources
should replace the entire collection with another collection. Based on this, when we had to support editing multiple items simultaneously, we wrote up this contract.{"resources": [{resource1},{resource2}]}
{"resources": [{"id":1,...},{"id":2,...}]}
We wrote the server half of the contract in Rails, but here's the client half (in CoffeeScript, sorry!):
I thought this was a lot easier to implement then overriding Backbone.sync. One comment on the code, our collections were always child objects, which should explain why the code sets a "parent_id" whenever an object is added to the collection, and how the root of the URL is the parent's URL. If you have root-level collections that you want to modify, then just remove the
@parent
business.