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.
- (function () {
-
- window.App = {
- Models: {},
- Collections: {},
- Views: {}
- };
-
- window.template = function (id) {
- return _.template($('#' + id).html());
- };
-
-
-
- App.Models.Person = Backbone.Model.extend({
- defaults: {
- name: 'Guest User',
- age: 30,
- occupation: 'worker'
- }
- });
-
-
-
- App.Collections.People = Backbone.Collection.extend({
- model: App.Models.Person
- });
-
-
-
-
- App.Views.People = Backbone.View.extend({
- tagName: 'ul',
-
- render: function () {
- this.collection.each(function (person) {
- var personView = new App.Views.Person({ model: person });
- this.$el.append(personView.render().el);
- }, this);
-
- return this;
- }
- });
-
-
-
- App.Views.Person = Backbone.View.extend({
- tagName: 'li',
-
- template: template('personTemplate'),
- render: function () {
- this.$el.html(this.template(this.model.toJSON()));
- return this;
- }
- });
-
-
- var peopleCollection = new App.Collections.People([
- {
- name: 'Mahesh Chand',
- age: 26
- },
- {
- name: 'Praveen',
- age: 25,
- occupation: 'Dotnet Developer'
- },
- {
- name: 'Sam Hobbs',
- age: 26,
- occupation: 'Java Developer'
- }
- ]);
-
-
- var peopleView = new App.Views.People({ collection: peopleCollection });
- $(document.body).append(peopleView.render().el);
- })();
SummaryIn this article, I explained how to use namespaces in Backbone.js. In a future articles we will understand more about Backbone.js with examples.