4

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!

andrewpthorp
  • 4,998
  • 8
  • 35
  • 56
  • http://documentcloud.github.com/backbone/#Collection-reset "Calling collection.reset() without passing any models as arguments will empty the entire collection." – asawyer Apr 04 '12 at 17:32
  • reset empties the collection, but it does not persist the state. In other words, when I reset the collection, lawnchair is not nuked. – andrewpthorp Apr 04 '12 at 17:36
  • I thought you where asking for a better way then clear state/fetch empty state. I suggested clear state/ reset collection. You could also override collection.reset to clear the state, and call the original reset. – asawyer Apr 04 '12 at 18:22

1 Answers1

3

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.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274