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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
<html > <head> <title></title> <script src="/scripts/jquery-1.8.3.js" type="text/javascript"></script> <script src="/scripts/underscore.js" type="text/javascript"></script> <script src="/scripts/backbone.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> var Movie = Backbone.Model.extend({ defaults: { mpaaRating: "NR" }, initialize: function() { console.log("Movie Model initialize"); } }); var Movies = Backbone.Collection.extend({ model: Movie, initialize: function() { console.log(""); console.log("Movie Collection initialize"); console.log(this); console.log(this.length); console.log(this.models); } }); var movie1 = new Movie({ "title": "Bag It", "averageUserRating": 4.6, "yearReleased": 2010, "mpaaRating": "R" }); var movie2 = new Movie({ "title": "Lost Boy: The Next Chapter", "averageUserRating": 4.6, "yearReleased": 2009, "mpaaRating": "PG-13" }); var movies = new Movies([movie1, movie2]); console.log(""); console.log(movies.length); console.log(movies.at(1).get("title")); </script> </body> </html> |
In the first section of the code we declare a Movie model class. There’s nothing special here.
Continue reading “Re-Learning Backbone.js – Collections”