Adding routes

I had a new JS project come up at work, so I’m taking time to extract my framework from the Gallery project into one that’s reusable for other projects. I should come up with a hipster name for it I suppose. Anyway, I put it on Github as App-Framework.

The Gallery didn’t need to manage multiple views and the URL routes were for  bookmarking to search results. I needed to extend my simple URL router module so that I could bind a controller function to a route change. Since I’d never done this or used a framework that did, this great post gave me a nudge in the right direction.

Setting up a route with the updated router module is pretty simple.

_router.when('/',{templateID:'test', controller:function(obj) {
  console.log('Running route: '+obj.route+', with template: '+obj.templateID);
}});

The when method will map the route (as a key/object property) to a controller function that’s run when the URL changes. Pretty handy.

My app framework utilizes commands for controller functions, so I needed create and addition utility function on my controller to map this to a command:

function mapRouteCommand(route, templateID, command) {
  _router.when(route,{templateID:templateID, controller:function executeRouteCommand(dataObj) {
    command.execute(dataObj);
  }});
}

Mapping is still simple:

mapRouteCommand('/', 'defaultView', _self.RouteInitialViewCommand);
mapRouteCommand('/1', 'test1', _self.RouteOneViewCommand);

From this point, it will call a method in the AppView to load/render/show the view.