简体   繁体   English

从Backbone.js中的集合中删除多个元素

[英]Remove multiple elements from a collection in Backbone.js

I have a Backbone.js collection and want to delete few elements from it at the same time. 我有一个Backbone.js集合,并希望同时删除它中的一些元素。 I want also remove view elements for the deleted models. 我还想删除已删除模型的视图元素。

The problem is that if I use collection.remove(arrayOfModels) , it fires up multiple DELETE requests. 问题是如果我使用collection.remove(arrayOfModels) ,它会激活多个DELETE请求。 This is bad performance wise, and also I might want to cancel deletion of the whole batch if something goes wrong. 这是性能不好的,如果出现问题,我可能还想取消整批的删除。 So instead I want to make a single request with the list of deleted elements as a parameter. 因此,我希望使用已删除元素列表作为参数发出单个请求。

What is the best approach here? 这里最好的方法是什么? Shall I override Backbone.sync and somehow aggregate ids of deleted elements to make a single request? 我是否应该覆盖Backbone.sync并以某种方式聚合已删除元素的ID来发出单个请求? Or just manually make a request and trigger 'remove' event for each of the deleted models to hide their views? 或者只是手动发出请求并为每个已删除的模型触发“删除”事件以隐藏其视图?

I think the most simple & clean approach is to make you own, specific ajax request, sending to the server the id's of the models you want to delete. 我认为最简单干净的方法是让你拥有特定的ajax请求,向服务器发送你想要删除的模型的id。

The server returns the id's of the models on success, and your ajax success callback can use that to remove those models from the collection. 服务器在成功时返回模型的id,您的ajax成功回调可以使用它来从集合中删除这些模型。 That will trigger the event for that the corresponding views listen for, so they hide themselves. 这将触发相应视图侦听的事件,因此它们隐藏自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM