How to empty a Backbone.js collection

32,590

Solution 1

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();

Solution 2

Personnaly i use:

_.invoke(collection.toArray(), 'destroy');

wich delete every element of the collection by calling the destroy method

Share:
32,590
Trevor Burnham
Author by

Trevor Burnham

Developer at HubSpot. Author of CoffeeScript: Accelerated JavaScript Development, Async JavaScript, and The npm Book.

Updated on May 21, 2021

Comments

  • Trevor Burnham
    Trevor Burnham almost 3 years

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

  • yves amsellem
    yves amsellem almost 13 years
    This will empty the collection on the client, not on the server.
  • Trevor Burnham
    Trevor Burnham almost 13 years
    Worth noting that as of Backbone 0.5.0, released today, refresh has been renamed reset (a much clearer name, IMHO).
  • jabbett
    jabbett over 9 years
    Note: Collection.reset() issues a single "reset" event at the end, per the docs. It does not trigger "remove" events on the models that have been removed.