Back to Home

How to use Routing in Ext JS 5

extjs · sencha · routing · routing

How to use Routing in Ext JS 5

Original author: Mitchell Simoens
  • Transfer
  • Tutorial

Routing is a new feature in Ext JS 5 that allows you to associate navigation history with the controller. The "Back / Forward" buttons are one of the main parts of the browser interface and with Ext JS 5 it has become very easy to make navigation in single-page applications.

Routing in Ext JS 5


Ext JS has always allowed us to handle the navigation history using the Ext.util.History class , but in Ext JS 5 we made this process even easier and more flexible. The router provides a simple configuration of the connection of hash tokens and controller methods with parameter support and route execution control ( Ext.util.History is used behind the scenes ). Let's look at a simple example:

    Ext.define('MyApp.controller.Main', {
        extend : 'Ext.app.Controller',
        routes : {
            'home' : 'onHome'
        },
        onHome : function() {}
    });


In the routes object, the home key is the hash, and onHome is the method in the controller that executes when it is clicked on it (for example:) localhost#home. To change the hash inside the controller, you can use the redirectTo method :

 this.redirectTo(‘home’); //редиректит на http://localhost#home

This will change the URL hash to #home , which in turn will call the onHome method , where the context will be the instance of the controller MyApp.controller.Main in which the route was defined. If you have the same route registered in several controllers, then the order of execution will be the same as in which the application controllers are registered (array of controllers ).

Hash Tokens and Parameters


A hash token may contain parameters, and the router passes them to the controller methods as arguments. The hash may look like '# user / 1234' , where 1234 is the user ID. To match this hash, the controller is configured as follows:

    Ext.define(‘MyApp.controller.Main', {
        extend : 'Ext.app.Controller',
        routes : {
            'user/:id' : 'onUser'
        },
        onUser : function(id) {}
    });

When configuring a route with parameters, a colon is placed before the parameter name. In this case, it is : id . The router will take any value passed and pass it to the onUser method . The order of the arguments passed to the method matches the order of the parameters defined in the route.

You can control the matching of hash parameters using regular expressions. In the example above, the ID can contain only numbers, and the rest of the values ​​should not match. The conditions config is used for this :

    Ext.define('Fiddle.controller.Main', {
        extend : 'Ext.app.Controller',
        routes : {
            'user/:id' : {
                action     : 'onUser',
                conditions : {
                    ':id' : '([0-9]+)'
                }
            }
        },
        onUser : function(id) {}
    });

This example shows two things: a route can be an object in which the action key is the controller method, and conditions is an object with parameters and regular expression strings. The reason the regular expression is written in the string is because the router creates the main expression based on the route parameters. The conditions config allows you to override the default regular expressions. The default regular expression for string parameters is '([% a-zA-Z0-9 \\ - \\ _ \\ s,] +)' .

To handle a route transition for which there are no matches, an unmatchedroute event exists . Its handler can be hung both on the application and on the controller. For example, on the controller:

    Ext.define('Fiddle.controller.Main', {
        extend : 'Ext.app.Controller',
        listen : {
            controller : {
                '*' : {
                    unmatchedroute : 'onUnmatchedRoute'
                }
            }
        },
        onUnmatchedRoute : function(hash) {}
    });

Sometimes it is necessary to catch a transition along a route in order to stop it or continue after some asynchronous action, for example, an ajax request. To do this, the before key is used in the route . Here is an example in which route execution continues after an ajax request:

    Ext.define('Fiddle.controller.Main', {
        extend : 'Ext.app.Controller',
        routes : {
            'user/:id' : {
                action     : 'onUser',
                before     : 'beforeUser',
                conditions : {
                    ':id' : '([0-9]+)'
                }
            }
        },
        beforeUser : function(id, action) {
            Ext.Ajax.request({
                url     : '/user/confirm',
                params  : {
                    userid : id
                },
                success : function() {
                    action.resume();
                },
                failure : function() {
                    action.stop();
                }
            });
        },
        onUser : function(id) {}
    });

The beforeUser method accepts the id argument , similar to onUser , as well as the action , which has the resume and stop methods that control the route. The action.resume () method will continue the route, allowing it to be made asynchronous, and action.stop () will prevent it from being executed. If true is passed to the stop method , then all routes will be stopped.

Ext JS applications are getting bigger and more complex, and they may require processing several hash tokens at the same time. In Ext JS 5, this feature is implemented, while each hash token is processed separately in its own sandbox. This means that if you cancel one route by passing true to the action.stop method , it will cancel the routes only by this hash token, and the rest will continue to execute. Each token must be divided by a vertical line:

    #user/1234|message/5ga

The router will split the hash and receive the tokens 'user / 1234' and 'message / 5ga' . First, it will process the user token , find all the routes matching it and execute them. If no routes matching this token are found, the unmatchedroute event is raised . Then the router will go to the message token and, by analogy, will find related routes. If not found, the unmatchedroute event is raised .

Conclusion


The new router in ExtJS 5 is easy to configure and also allows you to easily process your browser history, while it remains flexible and powerful to meet the requirements of complex applications. Together with MVC + VM, bidirectional data binding and other new features, Ext JS 5 is a great framework for enterprise applications.

Read Next