"How" to save an entire collection in Backbone.js
I am well aware it can be done and I've looked at quite a few places (including: Best practice for saving an entire collection?). But I'm still not clear "exactly how" is it written in code? (the post explains it in English. It'd be great to have a javascript specific explanation :)
Say I have a collection of models - the models themselves may have nested collections. I have overridden the toJSON() method of the parent collection and I am getting a valid JSON object. I wish to "save" the entire collection (corresponding JSON), but backbone doesn't seem to come in-built with that functionality.
var MyCollection = Backbone.Collection.extend({
model:MyModel,
//something to save?
save: function() {
//what to write here?
}
});
I know somewhere you have to say:
Backbone.sync = function(method, model, options){
/*
* What goes in here?? If at all anything needs to be done?
* Where to declare this in the program? And how is it called?
*/
}
Once the 'view' is done with the processing it is responsible for telling the collection to "save" itself on the server (capable of handling a bulk update/create request).
Questions that arise:
If it is indeed a tricky job then can we call jQuery.ajax within a view and pass the this.successMethod
or this.errorMethod
as success/error callbacks?? Will it work?
I need to get in sync with backbone's way of thinking - I know I'm definitely missing something wrt, syncing of entire collections.
My immediate thought is not to override the method on save method on Backbone.Collection but wrap the collection in another Backbone.Model and override the toJSON method on that. Then Backbone.js will treat the model as a single resource and you don't have to hack the way backone thinks too much.
Note that Backbone.Collection has a toJSON method so most of your work is done for you. You just have to proxy the toJSON method of your wrapper Backbone.Model to the Backbone.collection.
var MyCollectionWrapper = Backbone.Model.extend({
url: "/bulkupload",
//something to save?
toJSON: function() {
return this.model.toJSON(); // where model is the collection class YOU defined above
}
});
A very simple...
Backbone.Collection.prototype.save = function (options) {
Backbone.sync("create", this, options);
};
...will give your collections a save method. Bear in mind this will always post all the collection's models to the server regardless of what has changed. options are just normal jQuery ajax options.
I ended up just having a 'save' like method and called $.ajax within it. It gave me more control over it without the need to add a wrapper class as @brandgonesurfing suggested (although I absolutely love the idea :) As mentioned since I already had the collection.toJSON() method overridden all I landed up doing was using it in the ajax call...
Hope this helps someone who stumbles upon it...
链接地址: http://www.djcxy.com/p/67126.html上一篇: 保存整个集合的最佳实践?