Backbone.js Collections
Collections have a bunch of different usages in Backbone.js, but at their core they are basically arrays of models. If you are unfamiliar with Backbone models it might be a good idea to check out post on Backbone.js Models It’s a fairly quick introduction so it shouldn’t take too long to consume.
Collections, being groups of models, are good for displaying lists of data. So if you wanted, for example, to display a list of musical artists, the model would be an “Artist,” containing the artist name, birthday, hometown, favoriteColor or any other information that we’d want to use in our application, and the collection (array of models) would be “Artists.” To create a collection as an ordered set of models you have to specify which type of model your collection holds by setting the model property.
var Artists = Backbone.Collection.extend({
model: Artist
});
Again for demonstration, we’re going to actually need some models to use our collection. So let’s create one with some defaults (which we’ll be overriding anyway).
var Artist = Backbone.Model.extend({
defaults: {
name: 'New Artist',
birthday: 'January 1, 1970',
hometown: 'Los Angeles, CA',
favoriteColor: 'blue',
}
});
Now to instantiate a few models….
var biggie = new Artist({ id: 1, name: 'Notorious BIG', birthday: 'May 21, 1972', hometown: 'Brooklyn, NY', favoriteColor: 'green' });
var mike = new Artist({ id: 2, name: 'Mike Jones', birthday: 'January 6, 1981', hometown: 'Houston, TX', favoriteColor: 'blue' });
var taylor = new Artist({ id: 3, name: 'Taylor Swift', birthday: 'December 13, 1989', hometown: 'Reading, PA', favoriteColor: 'red' });
Note: When developing Backbone applications (or any other application for that matter) you’ll want to give your models an id property. It makes things much easier when working with lists and they’re required for doing any sort of retrieving and/or saving models from the database using the fetch and the save or sync methods.
Now that we have our models instantiated. We can use them in a collection. We can instantiate our new collection by passing in an array of models.
var artistArray = [biggie, mike, taylor]; var artists = new Artists(artistArray); console.log(JSON.stringify(artists));
Add, Remove, & Reset
To add models to a collection you can use the “add” method…
var jack = new Artist({ id: 4, name: 'Jack Johnson', birthday: 'May 18, 1975', hometown: 'North Shore, HI', favoriteColor: 'red' });
artists.add(jack);
console.log('Jack Johnson added...');
console.log(JSON.stringify(artists));
Note you can also add a model to the beginning of a collection by using the unshift method.
To remove a model from a collection, you can do this by providing the id of the model that you want to remove…
artists.remove(2);
console.log('Mike Jones removed...');
console.log(JSON.stringify(artists));
If you want to replace a collection with a completely new set of data (i.e. a new array of models), you can use the reset method. We’ve made a bunch of changes to our current collection. Let’s start over by passing the original array back in.
artists.reset(artistsArray);
console.log('Back to the beginning...');
console.log(JSON.stringify(artists));
Get & Set
If you need to get a value from a collection from somewhere else in your code, using the get method is fairly straightforward. You just have to pass in the id value to retrieve the model that you want to get…
console.log(JSON.stringify(artists.get(2)));
The set method for a collection has an interesting implementation, as described in the Backbone.js documentation…
The set method performs a “smart” update of the collection with the passed list of models. If a model in the list isn’t yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren’t present in the list, they’ll be removed.
So let’s take a look at this in action…
var cube = new Artist({ id: 2, name: 'Ice Cube', birthday: 'June 15, 1969', hometown: 'Los Angeles, CA', favoriteColor: 'pink' });
var katy = new Artist({ id: 5, name: 'Katy Perry', birthday: 'October 25, 1984', hometown: 'Santa Barbara, CA', favoriteColor: 'pink' });
artists.set([biggie, mike, jack, cube, katy]);
console.log('Setting artists...');
console.log(JSON.stringify(artists));
As you can see that’s what’s happened here. We’ve added a model that wasn’t yet in the collection (katy) so it was added. There was a model that was in the collection (taylor) that we didn’t include in our call to the “set” method. As a result, it was removed from the collection. We’ve also added a model (cube) that had the same ID as a model already in the list. As a result, the attributes of the old model are overwritten.
Hopefully that gives a good general introduction to what collections are. There are many other components of Backbone collections that aren’t entirely covered here that are useful when pieced together with the other building blocks of Backbone.js such as models and views. For more on collections you can view the Backbone.js Collections documentation here






0 Responses to Backbone.js Collections