I am dealing with a threaded comments collection, and when I delete a comment that has children, I do model.destroy()
for this comment, and on the server side all its branches get deleted.
I wrote a function that once a node is deleted from the tree, looks for all orphans and removes them too. So when I find orphans, I run model.destroy()
on them too but because they're already deleted on the server, sync returns errors.
Is there a way to disable sync for some destroy()
calls?
remove() The Backbone. js remove method is used to remove the view from the DOM. It calls stopListening to remove any bound events that the view has listenTo.
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
Who uses Backbone. js? 3467 companies reportedly use Backbone. js in their tech stacks, including Uber, Pinterest, and reddit.
This is kind of late but might work as an alternate solution for other people having the same problem.
Confronted with a very similar problem, I ended up setting all the children IDs to null
before calling destroy
on them. This way, backbone thinks that they are new and doesn't spawn a DELETE
HTTP request to the server upon removal.
deleteParent: function() {
this.model.children.each(function(child) {
// Set to null so that it doesn't try to spawn a 'DELETE' http request
// on 'destroy' since thinks its new (hack).
child.id = null;
child.destroy();
});
// This one DOES result in a 'DELETE' http request since it has an ID.
this.model.destroy();
},
Since all the destroy
method does is send a DELETE request and triggers destroy
, simply triggering destroy
is exactly what you're looking for.
model.trigger('destroy', model, model.collection, options);
Yeah, it feels a bit hackish, but that's pretty much all the Backbone code does anyway. If you want, and if you have a base model you extend from, you could add this as a method on that base model, and it might not feel quite so hackish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With