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!
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:
{id: parentId}
and updates the the all the categories with this data. 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.
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.
链接地址: http://www.djcxy.com/p/67130.html上一篇: Backbone.js多个模型子类的集合
下一篇: 如何使用backbone.js保存集合