Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone JS: how to disable sync for delete?

Tags:

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?

like image 558
mvbl fst Avatar asked Apr 18 '12 21:04

mvbl fst


People also ask

How do I delete a backbone view?

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.

How do I use backbone sync?

<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?

Who uses Backbone. js? 3467 companies reportedly use Backbone. js in their tech stacks, including Uber, Pinterest, and reddit.


2 Answers

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();
},
like image 24
fcarriedo Avatar answered Sep 22 '22 05:09

fcarriedo


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.

like image 133
Edward M Smith Avatar answered Sep 18 '22 05:09

Edward M Smith