Introduction

Welcome to the "Demonstrating Backbone.js" article series. This article demonstrates how to create and use collections in Backbone.js. This article starts with the concept of Backbone.js and various components of it. Previous articles have provided an introduction to views and the implementation of routers and collections. You can get them from the following:

In this article we will see how to use Namespaces.
Namespaces helps us to structure our application in a much nicer way and to keep the application with limited global variables.
See the inline comments for a better understanding.
  1. (function () { // entire block is wrapped into an anonymous jQuery function..
  2. window.App = { // defining app name space; we can rename it as per our project name.
  3. Models: {},
  4. Collections: {},
  5. Views: {}
  6. };
  7. window.template = function (id) {
  8. return _.template($('#' + id).html());
  9. };
  10. // Person Model
  11. App.Models.Person = Backbone.Model.extend({ // This is Person model referencing the App namespace model.
  12. defaults: {
  13. name: 'Guest User',
  14. age: 30,
  15. occupation: 'worker'
  16. }
  17. });
  18. // A List of People
  19. // Now here the People is referencing collection from App namespace
  20. App.Collections.People = Backbone.Collection.extend({
  21. model: App.Models.Person
  22. });
  23. // View for all people
  24. /// Now here People is referencing views from App namespace
  25. App.Views.People = Backbone.View.extend({
  26. tagName: 'ul',
  27. render: function () {
  28. this.collection.each(function (person) { // Change Person Reference from App Views namespace
  29. var personView = new App.Views.Person({ model: person });
  30. this.$el.append(personView.render().el);
  31. }, this);
  32. return this;
  33. }
  34. });
  35. // The View for a Person
  36. // Change Person Reference from App Views namespace
  37. App.Views.Person = Backbone.View.extend({
  38. tagName: 'li',
  39. template: template('personTemplate'),
  40. render: function () {
  41. this.$el.html(this.template(this.model.toJSON()));
  42. return this;
  43. }
  44. });
  45. // Change Person Reference from App Collections namespace
  46. var peopleCollection = new App.Collections.People([
  47. {
  48. name: 'Mahesh Chand',
  49. age: 26
  50. },
  51. {
  52. name: 'Praveen',
  53. age: 25,
  54. occupation: 'Dotnet Developer'
  55. },
  56. {
  57. name: 'Sam Hobbs',
  58. age: 26,
  59. occupation: 'Java Developer'
  60. }
  61. ]);
  62. // Change Person Views from App Views namespace
  63. var peopleView = new App.Views.People({ collection: peopleCollection });
  64. $(document.body).append(peopleView.render().el);
  65. })();
Summary

In this article, I explained how to use namespaces in Backbone.js. In a future articles we will understand more about Backbone.js with examples.