Search code examples
backbone.jscoffeescript

How to empty a Backbone.js collection


I was surprised to discover that this doesn't work:

coll = new Backbone.Collection
for i in [1..1000]
  coll.add new Backbone.Model()

console.log coll.length # 1000
coll.remove coll.models
console.log coll.length # 500!

I understand why this strange result occurs, more or less, though it seems like a bug to me. In any event, what's the best alternative, without resorting to internal methods like _reset (which wouldn't work anyway, as I want the appropriate remove event to be triggered)?


Solution

  • The easiest way to do this is to call .reset()[docs] on the collection.

    Calling collection.reset() without passing any models as arguments will empty the entire collection.

    i.e.

    collection.reset();