Controlling an Application with Router

On a normal website, a user navigates to and from different pages as they click links or fill out forms. However, in a single page application, a user’s interaction doesn’t load a new page. Instead, it is handled within a single page and components react to that interaction. So how do you still allow users to use the browser’s forward and back buttons? The answer is to digest URI hash changes with Ext JS 5’s new Router.

What Routing Is Used For

Routing can be used to track the application state through the use of the browser history stack. Routing also allows for deep linking into the application which allows a direct link to a specific part of your application.

What Routing Is Not Used For

Routing should not be used to store any data or session, data should be stored in a persistent data source such as a cookie or localstorage. Routing is only a means of tracking the application’s state.

What is the Hash?

Browsers navigate the internet using a URI which consists of many parts. Let’s look at a sample URI:

http://www.example.com/apps/users#user/1234

This should look relatively familiar. However, you may not recognize #user=1234 . This section of the URI is called the “hash” or fragment identifier. For more information on the hash, please read this resource http://en.wikipedia.org/wiki/Fragment_identifier . This hash provides a way for an application to control the history stack of the browser without reloading the current page. As the hash changes, the browser adds that whole URI to the history stack, which then allows you to utilize the browser’s forward / back buttons to traverse URIs including the hashes that may have changed. For instance, what happens if you update the hash to:

http://www.example.com/apps/users#user/5678

The browser fires a hashchange event that we can then utilize within the application.
A user can then click the back button to go back to the #user=1234 hash. This notification then allows you to react to the change within your application. It is important to mention that the hash is not sent to the server. The hash is typically digested within the client’s interpretation of the URI. The Ext Router relies on the browser’s hash functionality to allow application state tracking and deep linking.

Implement Routing in your Application

The Router class is a new addition to Ext JS 5 that was built to make hash change interpretation very simple in an MVC application. We have always had Ext.util.History, which you could use to react to the hash changes. However, this Ext.util.History offers a much more manual process and a proper Router class was needed. The Router provides simple integration into an Ext JS 5 MVC application by defining routes in a view controller. A route is a string that is matched to the hash and allows for deep linking within your Ext application. Here is a basic example controller implementing Router:

Ext.define('MyApp.view.main.MainController', {
    extend : 'Ext.app.ViewController',

    routes : {
        'users' : 'onUsers'
    },

    onUsers : function() {
        //...
    }
});

This route will react to the #users hash and will execute the onUsers method scoped to the controller instance. As you can see, the routes config is placed within the config object instead of on the root level.

Updating the Hash

To update the hash, a controller has a redirectTo method.

this.redirectTo('user/1234');

This will update the hash to be "#user/1234" and any routes configured to recognize the hash will be executed. There may be times that the current hash is the same as the hash that is trying to be updated to. In this case, redirectTo will return false and the hash will not get updated which will then not execute any configured routes. redirectTo also accepts a second parameter to force the Router to react to this hash by passing true

this.redirectTo('user/1234', true);

Even if the current hash matches the hash being passed to redirectTo , the Router will still execute any matching routes.

Default Token

When an application starts, it may be configured to add a default hash if one is not provided. For instance, if the application shows a dashboard when the #home hash is used, you may want to add the #home hash to the URI if no other hash exists. To enable a default hash, you can use the defaultToken config in the /app/view/Application.js file, which can be found within your application:

Ext.define('MyApp.Application', {
    extend : 'Ext.app.Application',

    //...

    defaultToken : 'home'
});

When the application is started, it will check the current hash of the URI. If there is a hash defined, it will execute the route handlers. If no hash is found, it will add the #home hash and any route handlers will get executed to handle it appropriately.

Hashes with Parameters

An application can also identify parameters within hashes. A user ID is an example of a parameter you may want to include in a hash. We mentioned using #user/1234 as a hash earlier within the guide. In this case, we may want the 1234 to be an id parameter. You would then set up your controller to react to the #user/1234 hash:

Ext.define('MyApp.view.main.MainController', {
    extend : 'Ext.app.ViewController',

    routes : {
        'user/:id' : 'onUser'
    },

    onUser : function(id) {
        //...
    }
});

The route we used was 'user/:id' and the colon, : . This signifies that there is a parameter and your application will pass that parameter to the onUser method as an argument. The method will receive the same number of arguments passed to it in the same order as specified in the route, which allows for easy inclusion of multiple parameters.

Hash Parameter Formatting

The application may want to enforce a specific format for the user ID. The ID is numeric In the case we’ve explored so far. You may also use the route to equate to an object by using the conditions config:

Ext.define('MyApp.view.main.MainController', {
    extend : 'Ext.app.ViewController',

    routes : {
        'user/:id' : {
            action     : 'onUser',
            conditions : {
                ':id' : '([0-9]+)'
            }
        }
    },

    onUser : function(id) {
        //...
    }
});

Let’s walk through this example. First, the ‘onUser’ method is now moved to the action config. This will work similarly to when we passed the string to the route. We then use the conditions config to provide an object. The key we want to control is the parameter name with the colon and we provide a Regular Expression string (not a Regular Expression object). For the :id condition, we use ([0-9]+) , which will allow numbers between 0 and 9 with any length and will remember the match. We use a string because a Regular Expression object is made to match the entire hash, so if there are multiple parameters in the route we need to concatenate the Regular Expression strings together into a single Regular Expression object. If you do not provide a condition for a parameter, it will default to:

([%a-zA-Z0-9\\-\\_\\s,]+)

Route Handling

There may be times when an application needs to prevent the handling of a route. In this case, we may want to check administrative rights to determine whether or not the current user is allowed to view a portion of the application. The route can be configured to use a before action, which may stop the current route, stop all routes or continue on with the route execution.

This example will continue the route execution:

Ext.define('MyApp.view.main.MainController', {
    extend : 'Ext.app.ViewController',

    routes : {
        'user/:id' : {
            before  : 'onBeforeUser',
            action  : 'onUser'
        }
    },

    onBeforeUser : function(id, action) {
        Ext.Ajax.request({
            url     : '/security/user/' + id,
            success : function() {
                action.resume();
            }
        });
    },

    onUser : function(id) {
        //...
    }
});

In the onBeforeUser method, the :id parameter is passed as an argument, but the last argument is an action . If you execute the resume method on the action , the route will continue to execute and the onUser method will then be called. Notice that we can wait for an AJAX request to complete before we need to continue the route execution.

We can expand on this example by telling the application to stop current route execution by executing the stop method:

Ext.define('MyApp.view.main.MainController', {
    extend : 'Ext.app.ViewController',

    routes : {
        'user/:id' : {
            before  : 'onBeforeUser',
            action  : 'onUser'
        }
    },

    onBeforeUser : function(id, action) {
        Ext.Ajax.request({
            url     : '/security/user/' + id,
            success : function() {
                action.resume();
            },
            failure : function() {
                action.stop();
            }
        });
    },

    onUser : function(id) {
        //...
    }
});

Ext JS applications can be complex and there may be many controllers set up to listen to the same route. However, only one controller is set up with a before action so there is only a single ajax request fired. If we pass true to the stop method of the action argument, we can then stop all queued routes from executing, not just the current route handling:

Ext.define('MyApp.view.main.MainController', {
    extend : 'Ext.app.ViewController',

    routes : {
        'user/:id' : {
            before  : 'onBeforeUser',
            action  : 'onUser'
        }
    },

    onBeforeUser : function(id, action) {
        Ext.Ajax.request({
            url     : '/security/user/' + id,
            success : function() {
                action.resume();
            },
            failure : function() {
                action.stop(true);
            }
        });
    },

    onUser : function(id) {
        //...
    }
});

Now, when the ajax request fails, we pass true to cancel all handlers for this route across all controllers.

Note: If you do not execute the resume or stop method, routing is interrupted and will never be completed properly. It’s important to execute either method at some point.

Handling Unmatched Routes

If the hash was changed but there is no route that was found to match the hash, the Router will do nothing; the Router will not attempt to change the hash and will leave the unmatched hash alone. The Router will fire the unmatchedroute event on the application instance which is listenable in the Ext.application call:

Ext.application({
    name : 'MyApp',

    listen : {
        controller : {
            '#' : {
                unmatchedroute : 'onUnmatchedRoute'
            }
        }
    },

    onUnmatchedRoute : function(hash) {
        //...
    }
});

Using Multiple Routes in a Single Hash

Since Ext JS applications can be complex, there may be times where we need to use multiple routes in a single hash. The Router is set up to handle this so there is no extra set up to the routes that are configured in the controllers. Instead, you can delimit the hash with a pipe: | . An example hash could be

`#user/1234|messages`

In this case, we want to show user details for the user with an id of 1234 , but also show messages. Each route will execute in the order dictated by the hash. They are then sandboxed from each other. In simpler terms, if you stop the user/1234 route, the messages route will continue execution. It’s important to note that the execution order of the individual routes is the same order as the routes are in the hash. The user/1234 route will always execute before the messages route for the above example.

You may modify the delimiter, by changing the Ext.app.route.Router.multipleToken property.

Last updated