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+")");
        // 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):

  // $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