Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 898
Trevor Burnham Avatar asked May 23 '11 19:05

Trevor Burnham


People also ask

What is collections in Backbone JS?

Advertisements. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.

How does Backbone js work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Why use Backbone js?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

What is Backbone in programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


2 Answers

Personnaly i use:

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

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

like image 33
Fassbender Avatar answered Oct 11 '22 04:10

Fassbender


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(); 
like image 147
Scott Harvey Avatar answered Oct 11 '22 03:10

Scott Harvey