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

Popular posts from this blog

File upload and Progress events with HTML5 XmlHttpRequest Level 2

The XmlHttpRequest Level 2 specification adds several enhancements to the XmlHttpRequest object. Last week I had blogged about cross-origin-requests and how it is different from Flash\Silverlight's approach .  With Level 2 specification one can upload the file to the server by passing the file object to the send method. In this post I'll try to explore uploading file using XmlHttpRequest 2 in conjunction with the progress events. I'll also provide a description on the new HTML5 tag -  progress which can be updated while the file is being uploaded to the server. And of course, some ColdFusion code that will show how the file is accepted and stored on the server directory.

Server sent events with HTML5 and ColdFusion

There are several ways to interact with the server apart from the traditional request\response and refresh all protocol. They are polling, long polling, Ajax and Websockets ( pusherapp ). Of all these Ajax and Websockets have been very popular. There is another way to interact with the server such that the server can send notifications to the client using Server Sent Events (SSE) . SSE is a part of HTML5 spec:  http://dev.w3.org/html5/eventsource/

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.