PageRenderTime 22ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/w6d6/backbonetutorials-gh-pages/_posts/2011-01-26-what-is-a-collection.md

https://gitlab.com/dhamme/App-Academy
Markdown | 65 lines | 47 code | 18 blank | 0 comment | 0 complexity | 16adee13c7f0cd3aae318c4d4046e4ac MD5 | raw file
  1. ---
  2. layout: post
  3. title: What is a collection?
  4. type: beginner
  5. posturl: http://backbonetutorials.com/what-is-a-collection
  6. ---
  7. # What is a collection?
  8. Backbone collections are simply an ordered set of [models](/what-is-a-model). Such that it can be used in situations such as;
  9. * Model: Student, Collection: ClassStudents
  10. * Model: Todo Item, Collection: Todo List
  11. * Model: Animal, Collection: Zoo
  12. Typically your collection will only use one type of model but models themselves are not limited to a type of collection;
  13. * Model: Student, Collection: Gym Class
  14. * Model: Student, Collection: Art Class
  15. * Model: Student, Collection: English Class
  16. Here is a generic Model/Collection example.
  17. {% highlight javascript %}
  18. var Song = Backbone.Model.extend({
  19. initialize: function(){
  20. console.log("Music is the answer");
  21. }
  22. });
  23. var Album = Backbone.Collection.extend({
  24. model: Song
  25. });
  26. {% endhighlight %}
  27. ## Building a collection
  28. Now we are going to populate a collection with some useful data.
  29. {% highlight javascript %}
  30. var Song = Backbone.Model.extend({
  31. defaults: {
  32. name: "Not specified",
  33. artist: "Not specified"
  34. },
  35. initialize: function(){
  36. console.log("Music is the answer");
  37. }
  38. });
  39. var Album = Backbone.Collection.extend({
  40. model: Song
  41. });
  42. var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
  43. var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });
  44. var song3 = new Song({ name: "Talk It Over In Bed", artist: "OMC" });
  45. var myAlbum = new Album([ song1, song2, song3]);
  46. console.log( myAlbum.models ); // [song1, song2, song3]
  47. {% endhighlight %}