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)?
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.
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.
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.
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).
Personnaly i use:
_.invoke(collection.toArray(), 'destroy');
wich delete every element of the collection by calling the destroy method
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With