Book Image

Backbone.js Cookbook

By : Vadim Mirgorod
Book Image

Backbone.js Cookbook

By: Vadim Mirgorod

Overview of this book

<p>There is no doubt that the superior rendering power of HTML5, thin-to-thick client transition and REST style communication created a new era in web development, replacing the outdated approach based on browser plugin technologies. Backbone.js allows developers to write lightweight, modular, and scalable JavaScript applications.<br /><br />Backbone.js Cookbook contains a series of recipes that provide practical, step-by-step solutions to the problems that may occur during frontend application development using an MVC pattern. You will learn how to build Backbone applications utilizing the power of popular Backbone extensions and integrating your app with different third party libraries. You will also learn how to fulfill the requirements of the most challenging tasks.<br /><br />The first chapter of the book introduces you to the MVC paradigm and teaches you how to architect rich Internet applications operating with basic concepts of Backbone.js. During the reading of this book you will learn how to solve challenging problems leveraging Backbone objects such as models, collections, views, routers, and so on.</p> <p><br />You learn how to use forms, layouts, templating engines, and other Backbone extensions, which will help you to complete specific features of your application. You will understand how to bind a model to a DOM element. You will see how perfectly Backbone.js integrates with third party libraries and frameworks such as jQuery, Zepto, Underscore.js, Require.js, Mustache.js, Twitter Bootstrap, jQueryMobile, PhoneGap and many others. This book will guide you in how to optimize and test your applications, create your own Backbone extensions, and share them with the open source community.</p> <p><br />With the help of Backbone.js Cookbook, you will learn everything you need to know to create outstanding rich Internet applications using the JavaScript programming language.</p>
Table of Contents (16 chapters)
Backbone.js Cookbook
Credits
About the Author
Acknowledgement
About the Reviewers
www.PacktPub.com
Preface
Index

Writing your first Backbone application


In this recipe, we are going to write our first Backbone application. Let it be a simple part of the billing system.

For example, we can implement a model and a view for the invoice item. Let's create InvoiceItemModel that contains the Quantity and Price fields and calculates the item's amount. We also need to have PreviewInvoiceItemView that is used to render a model.

The output of our demo application could be very simple, as shown in the following screenshot:

How to do it...

The new code in this recipe should go into the main.js file that we created in the previous recipe; we will do this as follows:

  1. Define the model by extending it from the Backbone.Model object.

      var InvoiceItemModel = Backbone.Model.extend({
    
        // Set default values.
        defaults: {
          price: 0,
          quantity: 0
        },
    
        // Calculate amount.
        calculateAmount: function() {
          return this.get('price') * this.get('quantity');
        }
      });

    In the InvoiceItemModel object, we have initialized the default values and performed the business logic, a function that calculates the total amount.

  2. Create a model instance.

        var invoiceItemModel = new InvoiceItemModel({
          price: 2,
          quantity: 3
        });
  3. Define the view that will render the model.

      var PreviewInvoiceItemView = Backbone.View.extend({
    
        // Define template using templating engine from
        // Underscore.js.
        template: _.template('\
          Price: <%= price %>.\
          Quantity: <%= quantity %>.\
          Amount: <%= amount %>.\
        '),
    
        // Render view.
        render: function () {
    
          // Generate HTML by rendering the template.
          var html = this.template({
    
            // Pass model properties to the template.
            price: this.model.get('price'),
            quantity: this.model.get('quantity'),
    
            // Calculate amount and pass it to the template.
            amount: this.model.calculateAmount()
          });
    
          // Set html for the view element using jQuery.
          $(this.el).html(html);
        }
      });

    As we can see, our view uses the this.model and this.el properties that are passed to the view when it is created.

        var previewInvoiceItemView = new PreviewInvoiceItemView({
          model: invoiceItemModel,
          el: 'body'
        });

    Inside a view, we used the jQuery library to set the content for the element associated with the view $(this.el).html(html). In our case, this.el contains 'body' that is also a jQuery selector.

    Such selectors are similar to CSS selectors and allow jQuery to find an arbitrary HTML element using the $() function.

  4. To render a view, we simply need to execute the render() method.

      previewInvoiceItemView.render();

    When rendering a view, we also used a templating engine provided by Underscore.js. This templating engine substitutes templates with data and outputs static HTML. More information about templates is available in the Using templates in a view recipe of Chapter 6, Templates, Forms, and UX Sugar.

  5. Start the application.

    There are several ways to start an application. If your application has only a single view, you can create a new instance of it and render it manually.

    An application should be started right after the HTML page is loaded. Let's write some code that will start a simple Backbone application:

      // When document is ready create the Model and show
      // the View.
      $(document).ready(function () {
    
        // Create InvoiceItemModel instance and set
        // model attributes.
        var invoiceItemModel = new InvoiceItemModel({
          price: 2,
          quantity: 3
        });
    
        // Create PreviewInvoiceItemView instance.
        var previewInvoiceItemView = new PreviewInvoiceItemView({
    
          // Pass our model.
          model: invoiceItemModel,
    
          // Set element where to render HTML.
          el: 'body'
        });
    
        // Render view manually.
        previewInvoiceItemView.render();
      });

See also