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

Go To StackoverFlow.com

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!

2012-04-04 17:23
by andrewpthorp
http://documentcloud.github.com/backbone/#Collection-reset "Calling collection.reset() without passing any models as arguments will empty the entire collection. - asawyer 2012-04-04 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 2012-04-04 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 2012-04-04 18:22


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.

2012-04-05 05:22
by Peter Lyons
Ads