Demonstrating Backbone.js: Sample Application

Introduction

Welcome to the "Demonstrating Backbone.js" article series. This article demonstrates how to use Backbone.js in a sample application. 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 Backbone.js in a simple store application that displays products.

Here we will use a Google web fonts style sheet  and customized style sheet.

google.css
  1. @font-face {  
  2.   font-family: 'PT Sans';  
  3.   font-style: normal;  
  4.   font-weight: 400;  
  5.   src: local('PT Sans'), local('PTSans-Regular'), url(http://themes.googleusercontent.com/static/fonts/ptsans/v5/LKf8nhXsWg5ybwEGXk8UBQ.woff) format('woff');  
  6. }  
  7. @font-face {  
  8.   font-family: 'PT Sans';  
  9.   font-style: normal;  
  10.   font-weight: 700;  
  11.   src: local('PT Sans Bold'), local('PTSans-Bold'), url(http://themes.googleusercontent.com/static/fonts/ptsans/v5/0XxGQsSc1g4rdRdjJKZrNBsxEYwM7FgeyaSgU71cLG0.woff) format('woff');  
  12. }  
Style.css
  1. /*------------------------- 
  2.     Simple reset 
  3. --------------------------*/  
  4.   
  5.   
  6. *{  
  7.     margin:0;  
  8.     padding:0;  
  9. }  
  10.   
  11.   
  12. /*------------------------- 
  13.     General Styles 
  14. --------------------------*/  
  15.   
  16.   
  17. html{  
  18.     background-color:#000000;  
  19. }  
  20.   
  21. body{  
  22.     font:15px/1.3 Arialsans-serif;  
  23.     color#4f4f4f;  
  24. }  
  25.   
  26. a, a:visited {  
  27.     outline:none;  
  28.     color:#389dc1;  
  29. }  
  30.   
  31. a:hover{  
  32.     text-decoration:none;  
  33. }  
  34.   
  35.   
  36.   
  37.   
  38. /*---------------------------- 
  39.     The main content element 
  40. -----------------------------*/  
  41.   
  42.   
  43. #main{  
  44.     padding:100px;  
  45.     background-color:#ccc;  
  46.     box-shadow:0 0 1px #ccc;  
  47.     width:700px;  
  48.     margin:100px auto;  
  49.     border-radius:6px;  
  50.     font:bold 24px/1 'PT Sans'sans-serif;  
  51.     color:#6b6b6b;  
  52. }  
  53.   
  54.   
  55. #main h1{  
  56.     font-size:36px;  
  57.     text-aligncenter;  
  58.     text-transformuppercase;  
  59.     padding0 0 80px;  
  60.   
  61. }  
  62.   
  63. #products{  
  64.     list-style:none;  
  65.     margin:0 auto;  
  66.     width:600px;  
  67. }  
  68.   
  69. #products li{  
  70.     background-color#fbfbfc;  
  71.     box-shadow:0 1px 1px #eee;  
  72.     font-size:22px;  
  73.     color#85898b;  
  74.     padding:22px 30px;  
  75.     margin-bottom:15px;  
  76.     border-radius:4px;  
  77.     cursor:pointer;  
  78. }  
  79.   
  80. #products li span{  
  81.     float:right;  
  82.     opacity:0.6;  
  83. }  
  84.   
  85. #products li input[type=checkbox]{  
  86.     border:1px solid #ccc;  
  87.     box-shadow:1px 1px 1px #ccc;  
  88.     margin-right:10px;  
  89.     width:16px;  
  90.     height:16px;  
  91.     display:inline-block;  
  92.     vertical-alignmiddle;  
  93. }  
  94.   
  95. #total{  
  96.     font-size:24px;  
  97.     text-align:right;  
  98.     width:570px;  
  99.     margin:30px auto 0;  
  100.     padding-right:30px;  
  101. }  
  102.   
  103. #total span{  
  104.     display:inline-block;  
  105.     min-width:70px;  
  106. }  
  107.   
  108.   
  109. #order{  
  110.     font:inherit;  
  111.     font-size:24px;  
  112.     cursor:pointer;  
  113.     border:none;  
  114.     display:block;  
  115.     background-color:#FFA500;  
  116.     color:#fff;  
  117.     text-transform:uppercase;  
  118.     width:200px;  
  119.     margin:80px auto 0;  
  120.     text-align:center;  
  121.     padding:22px 0;  
  122.     border-radius: 3px;  
  123.     box-shadow:0 1px 1px #ddd0 0 20px #84b8e0 inset;  
  124. }  
  125.   
  126. #order:hover{  
  127.     opacity: 0.9;  
  128. }  
Javascript.aspx
 
 In this app we will display the list of products in a store.

Please check the inline comments for a better understanding.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>  
  2.   
  3. <!DOCTYPE html>  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.   
  7.     <!-- Google web fonts -->  
  8.     <link href="css/google.css" rel="stylesheet" />  
  9.   
  10.     <!-- The main CSS file -->  
  11.      
  12.     <link href="css/style.css" rel="stylesheet" />  
  13.   
  14.   
  15. </head>  
  16. <body>  
  17.    <form id="main">  
  18.             <h1>Store</h1>  
  19.   
  20.             <ul id="products">  
  21.                 <!-- The products will be inserted here -->  
  22.             </ul>  
  23.   
  24.             <p id="total">total: <span>$0</span></p>  
  25.   
  26.             <input type="submit" id="order" value="Order" />  
  27.   
  28.         </form>  
  29.         <script type="text/javascript" src="backbone/Jquery.js"></script>  
  30.         <script type="text/javascript" src="backbone/underscore-min.js"></script>  
  31.         <script type="text/javascript" src="backbone/backbone-min.js"></script>  
  32.         <script>  
  33.             $(function () {  
  34.   
  35.                 // Create a model for the products  
  36.                 var Product = Backbone.Model.extend({  
  37.   
  38.                     // Will contain three attributes.  
  39.                     // These are their default values  
  40.   
  41.                     defaults: {  
  42.                         title: 'My products',  
  43.                         price: 500,  
  44.                         checkedfalse  
  45.                     },  
  46.   
  47.                     // Helper function for checking/unchecking a product  
  48.                     toggle: function () {  
  49.                         this.set('checked', !this.get('checked'));  
  50.                     }  
  51.                 });  
  52.   
  53.   
  54.                 // Create a collection of products  
  55.                 var ProductList = Backbone.Collection.extend({  
  56.   
  57.                     // Will hold objects of the Product model  
  58.                     model: Product,  
  59.   
  60.                     // Return an array only with the checked products  
  61.                     getChecked: function () {  
  62.                         return this.where({ checkedtrue });  
  63.                     }  
  64.                 });  
  65.   
  66.                 // Prefill the collection with a number of products.  
  67.                 var products = new ProductList([  
  68.                     new Product({ title: 'Iphone', price: 1200 }),  
  69.                     new Product({ title: 'Xperia', price: 1250 }),  
  70.                     new Product({ title: 'Galaxy Grand', price: 100 }),  
  71.                     new Product({ title: 'Google Nexus', price: 500 }),  
  72.                     new Product({ title: 'Macbook', price: 1500 }),  
  73.                     new Product({ title: 'Nokia Lumia', price: 1500 })  
  74.                     // Add more here  
  75.                 ]);  
  76.   
  77.                 // This view turns a Product model into HTML  
  78.                 var ProductView = Backbone.View.extend({  
  79.                     tagName: 'li',  
  80.   
  81.                     events: {  
  82.                         'click''toggleProduct'  
  83.                     },  
  84.   
  85.                     initialize: function () {  
  86.   
  87.                         // Set up event listeners. The change backbone event  
  88.                         // is raised when a property changes (like the checked field)  
  89.   
  90.                         this.listenTo(this.model, 'change'this.render);  
  91.                     },  
  92.   
  93.                     render: function () {  
  94.   
  95.                         // Create the HTML  
  96.   
  97.                         this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '<span>$' + this.model.get('price') + '</span>');  
  98.                         this.$('input').prop('checked'this.model.get('checked'));  
  99.   
  100.                       
  101.                         return this;  
  102.                     },  
  103.   
  104.                     toggleProduct: function () {  
  105.                         this.model.toggle();  
  106.                     }  
  107.                 });  
  108.   
  109.                 // The main view of the application  
  110.                 var App = Backbone.View.extend({  
  111.   
  112.                     // Base the view on an existing element  
  113.                     el: $('#main'),  
  114.   
  115.                     initialize: function () {  
  116.   
  117.                         // Cache these selectors  
  118.                         this.total = $('#total span');  
  119.                         this.list = $('#products');  
  120.   
  121.                         // Listen for the change event on the collection.  
  122.                         // This is equivalent to listening on every one of the   
  123.                         // product objects in the collection.  
  124.                         this.listenTo(products, 'change'this.render);  
  125.   
  126.   
  127.                         // Create views for every one of the products in the  
  128.                         // collection and add them to the page  
  129.   
  130.                         products.each(function (product) {  
  131.   
  132.                             var view = new ProductView({ model: product });  
  133.                             this.list.append(view.render().el);  
  134.   
  135.                         }, this);   // "this" is the context in the callback  
  136.                     },  
  137.   
  138.                     render: function () {  
  139.   
  140.                         // Calculate the total order amount by agregating  
  141.                         // the prices of only the checked elements  
  142.   
  143.                         var total = 0;  
  144.   
  145.                         _.each(products.getChecked(), function (elem) {  
  146.                             total += elem.get('price');  
  147.                         });  
  148.   
  149.                         // Update the total price  
  150.                         this.total.text('$' + total);  
  151.   
  152.                         return this;  
  153.   
  154.                     }  
  155.   
  156.                 });  
  157.   
  158.                 new App();  
  159.   
  160.             });  
  161.         </script>  
  162.   
  163.   
  164.      
  165. </body>  
  166. </html>  
Output
 
 
Summary

In this article, I explained how to use Backbone.js to make a simple store application. In future articles we will understand more about Backbone.js with examples.
 


Similar Articles