Javascript router

Let’s say you’re building a 3-pages website:

  1. Home
  2. User Settings -> Profile
  3. User Settings -> Account

Pretty basic. However, on the front end, you need to implement the following using Javascript:

  • Home page should have a carousel;
  • User Settings -> Profile should perform an AJAX request immediately after page loads;
  • User Settings -> Account should have a carousel, however, this time you must use another carousel plugin.

A non-trivial task and it’s really easy to mess up your Javascript code. So, how would you handle this?

In PHP + any MVC framework or Ruby + Merb/on Rails you use Router and Controllers to set different actions for different events.
So, why not just translate the current Controller, Action and Parameters to Javascript? Using the Javascript Router as a new abstraction layer you can easily handle separated javascript calls in just a single js file.

Here’s the source code of my Javascript/jQuery Router:

/*
* Router Class
*/
var Router = new function() {
    this.Controller = "",
    this.Action = "",
    this.Params = null,
    /*
     * Route method
     *
     * @param  string      Controller
     * @param  string      Action
     * @param  string      Params (JSON string)
     * @return void
     */
    this.route = function(Controller, Action, Params) {
        Router.Controller = Controller;
        Router.Action = Action;
        try {
            Router.Params = eval("("+Params+")");
            eval(Controller+"Controller."+Action+"()");
        }
        // Controller doesn't exists, not a big deal.
        catch (e) {
            Router.Params = null;
        }
    }
}

Now let’s delegate controller, action and parameters to the router right after a page loads (PHP+jQuery):

$(document).ready(function(){
  // $this->params is a key-value PHP array
  Router.route('<?= $this->controller ?>', '<?= $this->action ?>', '<?= json_encode($this->params) ?>');
});

Finally, we need to describe our Javascript controllers:

var HomeController = new function() {
    this.Index = function() {
        // $("#carousel").somecarouselplugin();
    }
}
var UserSettingsController = new function() {
    this.Profile = function() {
        // some ajax call
    },
    this.Account = function() {
       // $("#carousel").anothercarouselplugin();
    }
}

To access current Controller, Action and Parameters values from any of the controllers above, you can do something like this (I’m using jQuery dump plugin to output Params object):

alert("Controller: "+Router.Controller+", Action: "+Router.Action+", Params: "+$.dump(Router.Params));
Filed in: Web Development

Philip Tadros - Founder
Founder of Doejo an award winning Innovation Studio and INC 5,000 Company. Tadros also Founded and Manages Space by Doejo a Co-working loft in River North. Tadros was featured on CNBC “Planet of the Apps” and a Moxie Award winner. Tadros’s ability to build and support strong, diverse teams with collaborative cultures, coupled with preference for innovation, has made him an authority on design and technology. He maintains positive and growing relationships with clients at Doejo with Companies like Pandora, Wilson and Groupon as well has helped Doejo be recognized globally as one of twelve WordPress VIP partners including one of the largest media companies, Tribune Media, ranked 45 on Comscore covering over half of the US market. Tadros’ ability to grow Companies has allowed for facilitating Construction, Development, Design as well as cohesively building talented Teams.