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, and views with declarative event handling. It then all connects to your existing API over a RESTful JSON interface.
A Collection helps you deal with a group of related models. It loads and saves new models to the server and provides helper functions for performing aggregations or computations against a list of models. Aside from their own events, collections also proxy through all of the events that occur to models within them. This allows you to listen in one place for any change that might happen to any model in the collection.
In simpler words, a collection is is a group of models. Let’s look at the solved example below to understand it further.
So, you want to create a collection of chocolates in a chocolate box. Let’s look at the steps below:
<head>
tag:<script src=
"https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js">
</script>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js">
</script>
<script>
tag, define a new Model for single Chocolate
and also Collection
for a box:// Define a single Chocolate
var Chocolate = Backbone.Model.extend();
// Define a collection box.
var box = Backbone.Collection.extend({
model: Chocolate
});
Chocolate_box
and add some chocolates inside it using the .add
method. I have added some of my favorite chocolates below:// Define a chocolate box
var Chocolate_box = new box()
// Adding chocolates inside the box
Chocolate_box.add(new Chocolate({name : "Snickers"}));
Chocolate_box.add(new Chocolate({name : "Hershey's"}));
Chocolate_box.add(new Chocolate({name : "Twix"}));
Chocolate_box.add(new Chocolate({name : "Lindt"}));
Chocolate_box.add(new Chocolate({name : "KitKat"}));
length
, models
, and Id
of objects inside our collection. These can be accessed individually by the following commands:// length of our box
console.log(Chocolate_box.length)
// the models represented by our box
console.log(Chocolate_box.models)
// the Ids of models represented by our box
console.log(Chocolate_box._byId)
cid
values// accessing the model at index zero
console.log("Accessing element by index", Chocolate_box.at(0))
// using get to access the model using its Id.
console.log("Accessing element by ID", Chocolate_box.get("c1"))
// removing the model at index 0.
Chocolate_box.remove(Chocolate_box.at(0));
To further understand of these Backbone.Collection methods, click here.