问题
I provide a form for users to upload their own data. I use ajax-form-submit and then parse the data to create numerous models (one per row in uploaded csv).
Now, I want to create models into a predefined collection.
I can use add which takes an array of models but unfortunately, it does not send PUSH at server side. I know I can iterate and create .create for each model but let's say I have 10k models, it would create 10k calls. Sounds unreasonable. Did I miss anything?
The other way is to accept multiple models at server and use .ajax calls and then add manually to the collection for UI rendering.
Looking for the best route. Thanks.
回答1:
Backbone and REST simply do not cover all real-world use cases such as your bulk create example. Nor do they have an official pattern for bulk delete, which is also extremely common. I am baffled as to why they refuse to address these extremely common use cases, but in any case, you're left to your own good judgement here. So I would suggest adding a bulkSave
or import
method to your collection. That should send an AJAX POST request with your CSV form data to the server, the server should save the info and if all goes well, return a JSON array of the newly-created models. You collection should take that JSON array in the POST response and pass it to reset
(and parse
as well if you need special parsing).
Definitely don't do a POST request for each model (row in your CSV), especially if you plan on having 10K models. However, to be clear, it wouldn't be completely terrible to do that pattern for a few dozen models if your UI shows real-time progress and error handling on a per-record basis (23 of 65 saved, for example).
回答2:
I like the pragmatic approach of @PeterLyons but another idea could be trying to transform your not REST functionality to a REST functionality.
What you want is to create a bunch of Models at once. REST doesn't allow create multiple resources at one. What REST likes is to create one resource at a time.
No problem, we create a new resource call Bulk
with its own url and its own POST verb. The attributes
of this Model are the array of Models you want to create.
With this approach you can also solve future functionalities like modify and remove multiple Models at once.
Now you just need to figure out how to associate the array of Models to this new Model and how to make the Bulk.toJSON
method responses properly.
来源:https://stackoverflow.com/questions/10782510/backbone-create-multiple-models-in-collection-serverside