CoffeeScript Routing, part deux

I wrote a post not to long ago on how to roll your own JavaScript router. Our first version had named parameters, but we didn’t use them at all when calling the callbacks. Remembering the index of each parameter is a pain, so we’re going to fix that.

First things first, lets take a look at what we want to happen. Given the following route:

Route.add "/blog/:year/:month/:day", callbackMethod

We want the url http://www.example.com/blog/2012/02/07 to pass the following object to the callback:

{
  year: 2012,
  month: 02,
  day:07
}

Make it happen!

The first thing we need is a list of the named parameters in the route. We can get these by a using a simple regular expression before we process the route into a regular expression.

parameterNames = path.match(/:(\w*)/g)

Since this can, and should, differ wildly from route to route, we store those names on the same object that the route is on.

{
  params: path.match(/:(\w*)/g),
}

Now that we have the names of the parameters, we build a new params object to pass back to the callback

index = 1
params = {}
for name in route.params
  params[name.slice(1)] = matches[index++]

The resulting class now looks like this:

class Router
  clearRoutes: ->
    @routes = []
  @process: ->
    for route in @routes
      matches = window.location.pathname.match(route.path)
      if matches?
        index = 1
        params = {}
        for name in route.params
          params[name.slice(1)] = matches[index++]
        route.callback(params)
        return
  @add: (path, callback) ->
    @routes ||= []
    @routes.push { 
      params: path.match(/:(\w*)/g),
      path: new RegExp(path.replace(/\//g, "\\/").replace(/:(\w*)(?!(\w))/g, "(\\w*)")), 
      callback: callback 
    }

There you have it. A CoffeeScript stand alone router with named parameters. I’ve uploaded the resulting class along with its Jasmine tests to http://github.com/tbugai/coffeescript-router. For those of you in the ruby world, its also available as the coffeescript-router gem.

tim@collectiveidea.com

Comments

  1. November 22, 2018 at 10:01 AM

    The well described the CoffeeScript in this post. I hope that we will get this kind of stuff in the future also.