8 Router & Route - grid23/korbutJS GitHub Wiki

The Router class is a kind of dynamic switch, ie, a tool to select a way to answer a request depending on conditions. Routers are mostly seen as tool for managing urls, but they can be used in many different ways and contexts.


A route is by default a string. Although the Router can be tweaked to accept other inputs. Although there is no formal rule as to what kind of string value can be used with a router, there is a special meaning associated with string starting by character "/", ie, pathnames.

Possible kind of values in the context of routing pathnames:

  • "*" : matches all routes, matches are resolved before any other route, doesn't count on the number of matched routes for router.dispatchRoute()
  • "/foo/bar": matches only "/foo/bar"
  • "/foo/:bar": matches "/foo/foo", "/foo/biz" and so on...
  • "/foo/bar/": matches only "/foo/bar/"
  • "/foo/:bar/": matches "/foo/foo/", "/foo/biz/" and so on...
  • "/foo/:bar(.*)": matches "/foo/foo" and "foo/foo/" and "foo/foo/foo" and so on...
  • "/foo/:bar(fu|biz)": matches only "/foo/fu" and "/foo/biz"
  • "/foo/:bar([0-1])": matches only "/foo/0" and "/foo/1"

A routeHandler is either a single function, or any object with a handleRoute method.

A routeHandler is always invoked with the two arguments route and next. route is an instance of korbut.Route and yields information about the current route being matched. next is a function, which sends back the route in the routing process, to let other possible handlers to match it.

router.addRouteHandler("/foo/:bar/:fu", function(route, next){
router.dispatchRoute("/foo/my/route") // 1 - logs { bar: "my", fu: "route" }


korbut.getByUid(str uid"")

Returns the Router instance associated with the passed uid.

var router = new korbut.Router
var uid = router.uid
router === korbut.Router.getByUid(uid) // true
korbut.Router.isRouteHandler(fn|object routeHandler{}|())

Returns a boolean indicating the validity of the passed routeHandler. A valid routeHandler is either a function or any kind of object with a handleRoute method.

korbut.Router.isRouteHandler(function(){}) // true
korbut.Router.isRouteHandler({ handleRoute: function(){} }) // true
korbut.Router.isRouteHandler(1) // false
new korbut.Router(opt object routes{}, opt fn dispatcher(fn dispatch))

Returns an instance of Router. if routes is passed, router.addRouteHandler() will be invoked against it if dispatcher is passed, it will be invoked with dispatch as argument 0. dispatch is a shortcut to router.dispatchRoute.

router.addRouterHandler(object routes{ route: fn|object routeHandler()|{} })
router.addRouterHandler(str route, fn|object routeHandler{}|())

Registers handlers. Returns the number of added handlers.