Backbone - Create Multiple Models in Collection - serverside

大憨熊 提交于 2019-12-06 16:40:44

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).

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!