RequireJS: Application routing

Find the previous episode here.

Checkout the part2.0 branch
git checkout -b part2.0 origin/part2.0

In this section we will look into how a routing can be done. For this we are using another lightweight routing framework Page.js.  First install it using bower.

bower install visionmedia/page.js
We already had added the page in config.js. Now we need to create a router.js which will be in router folder.  
define(['page'], function(page) {

We will create a blank module with loading the page framework. Here we use the Module ID for the module which we defined in config.js. You could use the url also like "bower_components/page/page" But it would be better if a module id us used.

NOTE: In requireJS the .JS extension will not be used.

Next we will require the router module in app.js.
define(['config'], function(config) {
 "use strict";
This will load the router module after loading the config module.
Now we will look into the router module.
page('*', routerFn);
    function routerFn(ctx) {
     if (ctx.hash === 'home') { 
      require(['modules/home/HomeCtrl'], function(home) {

        }else if (ctx.hash === 'employee') {
        }else if (ctx.hash === 'project') {
        }else {
It's completely based on the path.js . You could refer the docs. We are starting the router and check the hash in the context and loading the appropriate module. Here we check the "#home" and loading the Home Module.
In HomeCtrl.js we will add the functionalities. 
define([], function() {
 function start(){

  start : start
Start will work as an constructor. As soon as the module and it's dependencies were loaded the it will start execute the code inside the function. The return object is necessory to access the start function from outside the module. You could read more of javascript scope here.
Next the home module start function need to called from router.
require(['modules/home/HomeCtrl'], function(home) {
You could click the home link and see the alert is working.
So our routing is complete and we will look into templating the home module in next part.


Don’t follow your role model. Be the Role model person for others. But it's so simple by getting Hadoop training in Chennai. Because it is an assurance course to bounce back from a double salary. For joining call 7502633633.

Popular posts from this blog

Configure PostgreSQL and phpPgAdmin in WAMP

Angular - 4 year road map

Flash FLV player using PHP