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.


Popular posts from this blog

Flash FLV player using PHP

Configure PostgreSQL and phpPgAdmin in WAMP

Angular4 - primeng, ngx-bootstrap

Change Android AVD location in Windows7

MEAN js Application structure