Skip to main content

On using PageJS as a Router and handling page refresh with pushState enabled

I have been looking at PageJS as a Routing solution for my Backbone applications. PageJS allows you to specify multiple callback functions for a particular route and creates a context object based on the current state of the application. The context object contains valuable information that can be used in constructing View components and in triggering business work flows.

Let's consider a simple application that lists Customers and Orders; also the application provides a functionality to search for customers based on the given ID. In this example application, there would be three routes - orders, customers and search. Using PageJS you can specify the routes using the page function:


Here, page.base is used to set the base path. This is required if your application is in a particular directory under the web root. The other set of lines define the various routes in the application. The first argument is the path mapping and it is followed by callback functions that should be triggered when the route is encountered. In my application, I would like to load the page first which includes loading several View components, triggering an Ajax request to get data from a RESTful service etc. Once this is complete, I would like components on the page to get a notification about the page change. The path mapping '*' is executed when none of the above routes match. This is useful if you want to redirect the user to an error document or a 404 page. Let's see the callback functions:

Notice that the first function 'loadPage' takes two arguments; the context object 'ctx' and the next callback function 'next'. The loadPage function then tries to load the corresponding page assets by calling a function loadPage on the PageManager module. The last line calls the function next; this would ask PageJS to trigger the next callback function. In this example the function 'triggerPageChangeEvent' is called.

The loadPage function uses the information available in the context (ctx) object to make decision on which page to load. The context object contains the following fields:

- canonicalPath: "/backbone-router/search"
- hash: ""
- params: Array[0]
- path: "/search"
- pathname: "/backbone-router/search"
- querystring: ""
- state: Object
  - path: "/backbone-router/search"
- title: "Backbone Router example"

A Context object is constructed at runtime when you navigate to a particular route. The state object is the pushState object and is available to the user to store application state variables. For example, if the user has searched for a Customer with ID 100, we can add this to the context's state:

context.state.selectedCustomer = this.model.toJSON();
context.save();

The save function will save the state of the application. If you look at the implementation in PageJS it uses replaceState function on the history object to save the state:

Context.prototype.save = function(){
    history.replaceState(this.state, this.title, this.canonicalPath);
};

When the user clicks on the back or forward button, the Context's state would be available. An Internal function in PageJS - onpopstate is called in this case. However, when the user explicitly triggers the page change by clicking on the link then a new Context object is created.

When working on this application I ran into a problem, wherein on clicking on the refresh button the application would not load. For example, if your URL reads '/backbone-router/customers' and you click the refresh button, the application would not load, which is a correct behavior. The web server would not be able to find the directory 'customers' under 'backbone-router' and the default error document would be shown. This can be handled by redirecting the user to the parent directory i.e. '/backbone-router' and loading the application. I use Apache web server and I can include a '.htaccess' file in the same directory and specify the redirection rules:

<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteRule (.*) index.html [L]
</ifModule>

The above redirection rule instructs the web server to redirect the user to index.html page if the file or the directory is not found. Now when you click on the refresh button, the index.html file would be loaded and the Context object would have the path field set to 'customers'. This will then load the required page.



Comments

  1. Really good article. I have one question regarding backbone.stickit is it possible to do reverse nested binding on forms?

    I have form like that:


    ...



    As a result I get model with attributes like:
    {
    title: "my new title",
    ... }


    But what I need is something like:
    {
    comments: {
    title: "my title",
    ...
    }
    }


    My current bindings:


    bindings:
    "#title": "title"
    ....

    ReplyDelete

Post a Comment

Popular posts from this blog

Custom validation messages for HTML5 Input elements using the constraint validation API

HTML5 has introduced several input types such as EMAIL, URL, RANGE, SEARCH, DATE, TIME, etc,. Most of the modern browsers have implemented them and are ready to be used in a HTML document. Another exciting feature introduced in HTML5 is the form validation. Instead of writing JavaScript to validate users input, browsers can now validate it and show an appropriate message if the validation fails. The validation message is shown in line with the field for which the validation has failed. The default error message is shown when the validation fails. In this post I'll explain how these error messages can be changed.

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code.

What is Minification?

Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript file…

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.