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. margin:0;
  6. padding:0;
  7. }
  8. /*-------------------------
  9. General Styles
  10. --------------------------*/
  11. html{
  12. background-color:#000000;
  13. }
  14. body{
  15. font:15px/1.3 Arial, sans-serif;
  16. color: #4f4f4f;
  17. }
  18. a, a:visited {
  19. outline:none;
  20. color:#389dc1;
  21. }
  22. a:hover{
  23. text-decoration:none;
  24. }
  25. /*----------------------------
  26. The main content element
  27. -----------------------------*/
  28. #main{
  29. padding:100px;
  30. background-color:#ccc;
  31. box-shadow:0 0 1px #ccc;
  32. width:700px;
  33. margin:100px auto;
  34. border-radius:6px;
  35. font:bold 24px/1 'PT Sans', sans-serif;
  36. color:#6b6b6b;
  37. }
  38. #main h1{
  39. font-size:36px;
  40. text-align: center;
  41. text-transform: uppercase;
  42. padding: 0 0 80px;
  43. }
  44. #products{
  45. list-style:none;
  46. margin:0 auto;
  47. width:600px;
  48. }
  49. #products li{
  50. background-color: #fbfbfc;
  51. box-shadow:0 1px 1px #eee;
  52. font-size:22px;
  53. color: #85898b;
  54. padding:22px 30px;
  55. margin-bottom:15px;
  56. border-radius:4px;
  57. cursor:pointer;
  58. }
  59. #products li span{
  60. float:right;
  61. opacity:0.6;
  62. }
  63. #products li input[type=checkbox]{
  64. border:1px solid #ccc;
  65. box-shadow:1px 1px 1px #ccc;
  66. margin-right:10px;
  67. width:16px;
  68. height:16px;
  69. display:inline-block;
  70. vertical-align: middle;
  71. }
  72. #total{
  73. font-size:24px;
  74. text-align:right;
  75. width:570px;
  76. margin:30px auto 0;
  77. padding-right:30px;
  78. }
  79. #total span{
  80. display:inline-block;
  81. min-width:70px;
  82. }
  83. #order{
  84. font:inherit;
  85. font-size:24px;
  86. cursor:pointer;
  87. border:none;
  88. display:block;
  89. background-color:#FFA500;
  90. color:#fff;
  91. text-transform:uppercase;
  92. width:200px;
  93. margin:80px auto 0;
  94. text-align:center;
  95. padding:22px 0;
  96. border-radius: 3px;
  97. box-shadow:0 1px 1px #ddd, 0 0 20px #84b8e0 inset;
  98. }
  99. #order:hover{
  100. opacity: 0.9;
  101. }
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. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <!-- Google web fonts -->
  6. <link href="css/google.css" rel="stylesheet" />
  7. <!-- The main CSS file -->
  8. <link href="css/style.css" rel="stylesheet" />
  9. </head>
  10. <body>
  11. <form id="main">
  12. <h1>Store</h1>
  13. <ul id="products">
  14. <!-- The products will be inserted here -->
  15. </ul>
  16. <p id="total">total: <span>$0</span></p>
  17. <input type="submit" id="order" value="Order" />
  18. </form>
  19. <script type="text/javascript" src="backbone/Jquery.js"></script>
  20. <script type="text/javascript" src="backbone/underscore-min.js"></script>
  21. <script type="text/javascript" src="backbone/backbone-min.js"></script>
  22. <script>
  23. $(function () {
  24. // Create a model for the products
  25. var Product = Backbone.Model.extend({
  26. // Will contain three attributes.
  27. // These are their default values
  28. defaults: {
  29. title: 'My products',
  30. price: 500,
  31. checked: false
  32. },
  33. // Helper function for checking/unchecking a product
  34. toggle: function () {
  35. this.set('checked', !this.get('checked'));
  36. }
  37. });
  38. // Create a collection of products
  39. var ProductList = Backbone.Collection.extend({
  40. // Will hold objects of the Product model
  41. model: Product,
  42. // Return an array only with the checked products
  43. getChecked: function () {
  44. return this.where({ checked: true });
  45. }
  46. });
  47. // Prefill the collection with a number of products.
  48. var products = new ProductList([
  49. new Product({ title: 'Iphone', price: 1200 }),
  50. new Product({ title: 'Xperia', price: 1250 }),
  51. new Product({ title: 'Galaxy Grand', price: 100 }),
  52. new Product({ title: 'Google Nexus', price: 500 }),
  53. new Product({ title: 'Macbook', price: 1500 }),
  54. new Product({ title: 'Nokia Lumia', price: 1500 })
  55. // Add more here
  56. ]);
  57. // This view turns a Product model into HTML
  58. var ProductView = Backbone.View.extend({
  59. tagName: 'li',
  60. events: {
  61. 'click': 'toggleProduct'
  62. },
  63. initialize: function () {
  64. // Set up event listeners. The change backbone event
  65. // is raised when a property changes (like the checked field)
  66. this.listenTo(this.model, 'change', this.render);
  67. },
  68. render: function () {
  69. // Create the HTML
  70. this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '<span>$' + this.model.get('price') + '</span>');
  71. this.$('input').prop('checked', this.model.get('checked'));
  72. return this;
  73. },
  74. toggleProduct: function () {
  75. this.model.toggle();
  76. }
  77. });
  78. // The main view of the application
  79. var App = Backbone.View.extend({
  80. // Base the view on an existing element
  81. el: $('#main'),
  82. initialize: function () {
  83. // Cache these selectors
  84. this.total = $('#total span');
  85. this.list = $('#products');
  86. // Listen for the change event on the collection.
  87. // This is equivalent to listening on every one of the
  88. // product objects in the collection.
  89. this.listenTo(products, 'change', this.render);
  90. // Create views for every one of the products in the
  91. // collection and add them to the page
  92. products.each(function (product) {
  93. var view = new ProductView({ model: product });
  94. this.list.append(view.render().el);
  95. }, this); // "this" is the context in the callback
  96. },
  97. render: function () {
  98. // Calculate the total order amount by agregating
  99. // the prices of only the checked elements
  100. var total = 0;
  101. _.each(products.getChecked(), function (elem) {
  102. total += elem.get('price');
  103. });
  104. // Update the total price
  105. this.total.text('$' + total);
  106. return this;
  107. }
  108. });
  109. new App();
  110. });
  111. </script>
  112. </body>
  113. </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.