Backbone.js is a popular JavaScript library for building web applications with a rich set of features. One of its key features is the ability to work with collections, which allow you to manage collections of models in a structured way.

What are Collections?

In Backbone.js, a collection is a group of models. Collections provide a way to store, retrieve, and manipulate a collection of models. They are similar to arrays, but they also have methods for adding, removing, and querying models.

Key Features of Collections

  • Adding and Removing Models: Collections provide methods to add and remove models, such as add(), remove(), and reset().
  • Querying Models: Collections have methods to query models, such as get(), where(), and find().
  • Serializing and Deserializing: Collections can be serialized to and deserialized from JSON, making them easy to work with on the server side.

Example Usage

Here's an example of how to create a collection and add models to it:

var MyCollection = Backbone.Collection.extend({
  model: MyModel
});

var myCollection = new MyCollection([
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' }
]);

myCollection.add({ id: 3, name: 'Item 3' });

Working with Views

Collections are often used in conjunction with views. A view can be bound to a collection, and it will automatically update when the collection changes.

var MyView = Backbone.View.extend({
  template: _.template('<ul><% _.each(this.collection.models, function(model) { %><li><%= model.get('name') %></li><% }); %></ul>'),
  initialize: function() {
    this.collection.on('add remove reset', this.render, this);
  },
  render: function() {
    this.$el.html(this.template({ collection: this.collection }));
  }
});

var myView = new MyView({ collection: myCollection });
$('#my-ul').html(myView.render().el);

Further Reading

For more information on Backbone.js and collections, check out the following resources:

Backbone.js Collections