How to save a collection using backbone.js

I have a hierarchy of categories. I use the jquery library for the hierarchy so that everything mixes up as the user wants. Then click "Save." Thus, the original hierarchy and the hierarchy that must be preserved can be completely different.

The hierarchy is presented as a collection, and I use parentIds to build the tree using the ol and li tags.

When the user clicks the "Save" button, I need to update all the elements of the collection with their new parentId and synchronize each with the server.

I am wondering if anyone has any tips on how to proceed here. I saw in the documentation for Backbone.sync "Use setTimeout to batch update quick updates in a single request." So, if I understood correctly, would I queue each of the Backbone.sync calls and then use setTimeout to send my queue to the server in a few seconds?

Also, if I rewrite Backbone.sync, I don’t need the save method somewhere for a collection that will parse the json response (the server response should send a list of objects) and then call model.set for each item in the collection? Does anyone have sample code?

Thank!

+7
jquery model-view-controller
Nov 02 '11 at 2:52
source share
2 answers

I'm not sure I fully understand the context. This is something like this: you have one collection with all categories and keep the hierarchy using the parentId property. The user changes the hierarchy, and then you want to save the hierarchy (implicitly, save the collection, which now contains different parentId ).

If this is correct, I would do the following:

  • make a PUT / categories action that takes the hash {id: parentId} and updates all categories with this data.
  • when saving, I would call Backbone.sync('update', categories_collection, {data: a_hash_of_{id:parent_id}, success: your_success_callback) . This should work without any other overrides if you specify a url for your categories, and in the success callback you can simply reset to collect new data.

This is not a complete REST, but it has the advantage that only one update request is fired no matter how many categories you have.

+6
Nov 02 '11 at 11:31
source share

I ended up introducing the updateAll method into my collectible model. It worked like a dream:

 Domain.PageList = Backbone.Collection.extend({ model: Domain.Page, url: '_domainController/PageListController', comparator: function(page) { return page.get('ordering'); }, updateAll: function() { var collection = this; options = { success: function(model, resp, xhr) { collection.reset(model); } }; return Backbone.sync('update', this, options); } }); 

On the server (I use PHP) I just get the data and save it in my database and return a new collection in JSON format.

+21
Nov 02 '11 at 20:35
source share



All Articles