Search code examples
backbone.jsjavascriptlawnchair

Clear all elements from Backbone Collection and remove them from the associated Lawnchair


I am using Backbone.js, Lawnchair, and backbone.lawnchair.js.

I was wondering what the correct way to "empty" a collection (both from the application and from localStorage) would be?

Currently, I am employing something along these lines:

Favorites.Collection = Backbone.Collection.extend({
  model: Favorites.Model,
  lawnchair: new Lawnchair({ name: "favorites" }, function(e){}),

  empty: function(){
    this.lawnchair.nuke();
    this.fetch();
  }
});

This is essentially destroying the elements in localStorage (lawnchair provides the nuke method) and fetching from localStorage. This seems a bit clunky, and I was wondering if I am thinking about this right - or if there is a better way.

Cheers!


Solution

  • Backbone follows sort of RESTish principles and sadly REST doesn't describe a bulk-delete procedure. Resources can only be deleted one at a time. Typically APIs don't support HTTP DELETE on the entire collection URI like DELETE /favorites, only DELETE /favorites/42 - one at a time. Thus there's no single backbone method that just does this as generally the collection is mostly designed to do fetch/GET and then delegate to the individual models to do saves and deletes. So yes, you're on your own for a bulk-delete approach. You can do something more RPC-like and pass a list of IDs to a delete procedure, but what you have above seems perfectly adequate to me, and yes deleting them all directly and then re-fetching the collection seems also very reasonable to me. So I think you're solution is fine as is, but I'm also curious to see what others suggest.