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

Implementing URL routing in your application


The Backbone.Router object is used for navigation inside your application. You should use it if you want to access different view pages by hitting the appropriate URLs. Users can also navigate through an application using the browser's history bar.

By default, the router works well with hash paths, such as index.html#path/to/page. Any string that is placed after a hash character is supposed to be a route and is processed by Backbone.Router.

How to do it...

Here, we are going to explain how to create our own router in our application:

  1. Define a router by extending Backbone.Router into the Workspace object and setting pairs of routes and callback functions for them inside the routes property that is passed to the extend() method. This gives the router information of which callback should be executed in case the appropriate route is accessed.

      var Workspace = Backbone.Router.extend({
        routes: {
          // Default path.
          '': 'invoiceList',
    
          // Usage of static path.
          'invoice': 'invoiceList',
        },
      });
  2. Add a callback method to the router object.

        invoiceList: function() {
          var invoiceListView = new InvoiceListView({
            el: 'body'
          });
          invoiceListView.render();
        }

    If the user visits index.html or index.html#invoice, the invoiceList() callback is executed, which renders InvoiceListView. Here, InvoiceListView is a simple stub.

  3. Tell Backbone to use this router and start the application.

      $(document).ready(function () {
        new Workspace();
        Backbone.history.start();
      });

    Here, we create a new Workspace object and execute the start() method of the Backbone.history object that is used for global application routing. As always, we should start our application right after the HTML page has loaded completely.

How it works...

Backbone.Router is used just for defining routes and callbacks. All the important jobs are done by Backbone.history that serves as a global router (per frame) to handle hashchange or pushState events, match the appropriate route, and trigger callbacks. You shouldn't ever have to create an instance of the global router—you should use the reference to Backbone.history that will be created for you automatically if you make use of routers with routes.

There's more...

Backbone router allows the defining of routes with parameters, which we are going to explain in this section.

Parsing parameters in a URL

If we want the router to parse parameters in a URL, we need to use the colon character (:) before the parameter's name. Here is an example that demonstrates how Backbone.Router parses URLs with a parameter.

  var Workspace = Backbone.Router.extend({
    routes: {
      // Usage of fragment parameter.
      'invoice/:id': 'invoicePage',
    },

    // Shows invoice page.
    invoicePage: function(id) {
      var invoicePageView = new InvoicePageView({
        el: 'body',

        // Pass parameter to the view.
        id: id
      });
      invoicePageView.render();
    },
  });

Paths such as index.html#invoice/1 and index.html#invoice/2 will be parsed by a router. In both cases, the invoicePage() callback is executed; it passes the ID parameter to InvoiceLPageView and renders it.

Tip

Validate parameters in your router

There is no default way to set a restriction for the data type or format of the parameters inside the routes definition. All parameters that are passed to the router callbacks are strings, and it is up to the developer to validate them.

See also

  • The Handling router events recipe in Chapter 5, Events and Bindings

  • The Switching views using Backbone.Router recipe in Chapter 4, Views