Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

jquery - How to save a Collection with backbone.js

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...