Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. 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? Or just manually make a request and trigger 'remove' event for each of the deleted models to hide their views?

like image 914
kulesa Avatar asked Feb 16 '26 13:02

kulesa


1 Answers

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.

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. That will trigger the event for that the corresponding views listen for, so they hide themselves.

like image 188
dira Avatar answered Feb 19 '26 01:02

dira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!