7
votes

I have a hierarchy of categories. I use a jquery library for the hierarchy to get all jumbled up the way the user wants. Then they click save. So the initial hierarchy and hierarchy to be saved could be totally different.

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

When the user clicks save, I then need to update all the items in the collection with their new parentId and sync each one with the server.

I'm wondering if anyone has any advice on how to proceed here. I've seen in the documentation for Backbone.sync, ''Use setTimeout to batch rapid-fire updates into a single request.'' So, if I understand correctly, I would queue each of the calls to Backbone.sync and then use setTimeout to send my queue to the server after a few seconds?

Also, if I rewrite Backbone.sync, don't I still need a 'save' method somewhere for the collection that will parse the json of the response (the server response would have to send back a list of objects) and then call model.set on each item in the collection? Does any one have any example code?

Thanks!

2

2 Answers

21
votes

I ended up putting an updateAll method into my collection model. This 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 backend (I'm using PHP) I just get the data and save it to my database and return a new collection in JSON format.

6
votes

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

If that is correct, what I would do is:

  • make a PUT /categories action that accepts a hash of {id: parentId} and updates the the all the 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 overriding, if you specify url for your categories, and in the success callback you can simply reset the collection with the new data.

This is not full REST, but it has the advantage of firing only one update request no matter how many categories you have.