Re-Learning Backbone.js – Collections

Backbone.js collections are used to store and manage a group of similar or related objects. If all we wanted to do was store related objects we could use a JavaScript array, but Backbone.js Collection provides an infrastructure that allows us to manage the set of data more effectively and efficiently.

As usual, I will attempt to keep the sample very simple. We will focus on collections, but we will need the assistance of models in this example.

In the following example we are creating 2 models and adding them to a collection.

In the first section of the code we declare a Movie model class. There’s nothing special here.

Next, we declare a Movies collection class. This is very similar to declaring a Movie model class. The only difference for us is that the collection has a property called “model”. We assigned the Movie class to the collection “model” property. This tells the collection that the type of models that will be manage will be “Movie” type.

We then create 2 movie objects. Again, there’s nothing special here.

Now we finally create the “movies” collection. We also pass in the two “movie” objects that we created. We can see in the results that when the collection’s initialize method gets called the collection does not include the models that were passed in. This seems a little odd to me, but I guess this is the way it works.

After the movies collection object is created, we can work with the objects that the collection is managing.

************************************************************

The primary purpose of this example is to show how collection events work.

In this code whenever a new movie is added, the “movieAdded” method should be called. And whenever an individual movie’s property is changed, then call the method “movieChange”.

In the previous code we create two methods, “movieAdded”, “movieChange”. These methods are bound to the collection movies. When the “add” event is triggered, call the method “movieAdded”. When the “change” event is triggered, call the method “movieChange”

We create a need movie and add it to the movies collection. At this time the “movieAdded” method should be triggered.

We then change the title and yearReleased of an individual movie. This should trigger the “movieChange” method.

 

Leave a Reply

Your email address will not be published. Required fields are marked *