Synopsis
Director is a router. Routing is the process of determining what code to run when a URL is requested.
Motivation
A routing library that works in both the browser and node.js environments with as few differences as possible. Simplifies the development of Single Page Apps and Node.js applications. Dependency free (doesn't require jQuery or Express, etc).
Status
Features
Usage
Building client-side script
Run the provided CLI script.
./bin/build
Client-side Routing
It simply watches the hash of the URL to determine what to do, for example:
http://foo.com/#/bar
Client-side routing (aka hash-routing) allows you to specify some information about the state of the application using the URL. So that when the user visits a specific URL, the application can be transformed accordingly.
Here is a simple example:
A Gentle Introduction #/author #/books #/books/view/1
Director works great with your favorite DOM library, such as jQuery.
A Gentle Introduction 2 Author Name Book1, Book2, Book3 #/author #/books
You can find a browser-specific build of director
here which has all of
the server code stripped away.
Server-Side HTTP Routing
Director handles routing for HTTP requests similar to journey
or express
:
// // require the native http module, as well as director. // var http = director = ; // // create some logic to be routed to. // { thisres thisres; } // // define a routing table. // var router = '/hello': get: helloWorld ; // // setup a server and when there is a request, dispatch the // route that was requested in the request object. // var server = http; // // You can also do ad-hoc routing, similar to `journey` or `express`. // This can be done with a string or a regexp. // router; router; // // set the server to listen on port `8080`. // server;
See Also:
- Auto-generated Node.js API Clients for routers using Director-Reflector
- RESTful Resource routing using restful
- HTML / Plain Text views of routers using Director-Explorer
Server-Side CLI Routing
Director supports Command Line Interface routing. Routes for cli options are
based on command line input (i.e. process.argv
) instead of a URL.
var director = ;var router = ;router;router;// You will need to dispatch the cli arguments yourselfrouter;
Using the cli router, you can dispatch commands by passing them as a string.
For example, if this example is in a file called foo.js
:
$ node foo.js createcreate something$ node foo.js destroydestroy something
API Documentation
- Constructor
- Routing Table
- Adhoc Routing
- Scoped Routing
- Routing Events
- Configuration
- URL Matching
- URL Parameters
- Wildcard routes
- Route Recursion
- Async Routing
- Resources
- History API
- Instance Methods
- Attach Properties to
this
- HTTP Streaming and Body Parsing
Constructor
var router = ;
Routing Table
An object literal that contains nested route definitions. A potentially nested set of key/value pairs. The keys in the object literal represent each potential part of the URL. The values in the object literal contain references to the functions that should be associated with them. bark and meow are two functions that you have defined in your code.
//// Assign routes to an object literal.//var routes =//// a route which assigns the function `bark`.//'/dog': bark//// a route which assigns the functions `meow` and `scratch`.//'/cat': meow scratch;//// Instantiate the router.//var router = ;
Adhoc Routing
When developing large client-side or server-side applications it is not always
possible to define routes in one location. Usually individual decoupled
components register their own routes with the application router. We refer to
this as Adhoc Routing. Lets take a look at the API director
exposes for
adhoc routing:
Client-side Routing
var router = ;router;
HTTP Routing
var router = ;router;
Scoped Routing
In large web appliations, both Client-side and Server-side, routes are often scoped within a few individual resources. Director exposes a simple way to do this for Adhoc Routing scenarios:
var router = ;//// Create routes inside the `/users` scope.//router;
Routing Events
In director
, a "routing event" is a named property in the
Routing Table which can be assigned to a function or an Array
of functions to be called when a route is matched in a call to
router.dispatch()
.
- on: A function or Array of functions to execute when the route is matched.
- before: A function or Array of functions to execute before calling the
on
method(s).
Client-side only
- after: A function or Array of functions to execute when leaving a particular route.
- once: A function or Array of functions to execute only once for a particular route.
Configuration
Given the flexible nature of director
there are several options available for
both the Client-side and Server-side. These
options can be set using the .configure()
method:
var router = routes;
The options
are:
- recurse: Controls route recursion. Use
forward
,backward
, orfalse
. Default isfalse
Client-side, andbackward
Server-side. - strict: If set to
false
, then trailing slashes (or other delimiters) are allowed in routes. Default istrue
. - async: Controls async routing. Use
true
orfalse
. Default isfalse
. - delimiter: Character separator between route fragments. Default is
/
. - notfound: A function to call if no route is found on a call to
router.dispatch()
. - on: A function (or list of functions) to call on every call to
router.dispatch()
when a route is found. - before: A function (or list of functions) to call before every call to
router.dispatch()
when a route is found.
Client-side only
- resource: An object to which string-based routes will be bound. This can be especially useful for late-binding to route functions (such as async client-side requires).
- after: A function (or list of functions) to call when a given route is no longer the active route.
- html5history: If set to
true
and client supportspushState()
, then uses HTML5 History API instead of hash fragments. See History API for more information. - run_handler_in_init: If
html5history
is enabled, the route handler by default is executed uponRouter.init()
since with real URIs the router can not know if it should call a route handler or not. Setting this tofalse
disables the route handler initial execution. - convert_hash_in_init: If
html5history
is enabled, the window.location hash by default is converted to a route uponRouter.init()
since with canonical URIs the router can not know if it should convert the hash to a route or not. Setting this tofalse
disables the hash conversion on router initialisation.
URL Matching
var router =;
Routes can sometimes become very complex, simple/:tokens
don't always
suffice. Director supports regular expressions inside the route names. The
values captured from the regular expressions are passed to your listener
function.
var router =;
var router =;
URL Parameters
When you are using the same route fragments it is more descriptive to define
these fragments by name and then use them in your
Routing Table or Adhoc Routes. Consider a
simple example where a userId
is used repeatedly.
//// Create a router. This could also be director.cli.Router() or// director.http.Router().//var router = ;//// A route could be defined using the `userId` explicitly.//router;//// Define a shorthand for this fragment called `userId`.//router;//// Now multiple routes can be defined with the same// regular expression.//router;router;
Wildcard routes
It is possible to define wildcard routes, so that /foo and /foo/a/b/c routes to
the same handler, and gets passed ""
and "a/b/c"
respectively.
router { });
Route Recursion
Can be assigned the value of forward
or backward
. The recurse option will
determine the order in which to fire the listeners that are associated with
your routes. If this option is NOT specified or set to null, then only the
listeners associated with an exact match will be fired.
No recursion, with the URL /dog/angry
var routes ='/dog':'/angry'://// Only this method will be fired.//on: growlon: bark;var router = ;
backward
, with the URL /dog/angry
Recursion set to var routes ='/dog':'/angry'://// This method will be fired first.//on: growl//// This method will be fired second.//on: bark;var router = ;
forward
, with the URL /dog/angry
Recursion set to var routes ='/dog':'/angry'://// This method will be fired second.//on: growl//// This method will be fired first.//on: bark;var router = ;
Breaking out of recursion, with the URL /dog/angry
var routes ='/dog':'/angry'://// This method will be fired first.//{ return false; }//// This method will not be fired.//on: bark;//// This feature works in reverse with recursion set to true.//var router = ;
Async Routing
Before diving into how Director exposes async routing, you should understand Route Recursion. At it's core route recursion is about evaluating a series of functions gathered when traversing the Routing Table.
Normally this series of functions is evaluated synchronously. In async routing, these functions are evaluated asynchronously. Async routing can be extremely useful both on the client-side and the server-side:
- Client-side: To ensure an animation or other async operations (such as HTTP requests for authentication) have completed before continuing evaluation of a route.
- Server-side: To ensure arbitrary async operations (such as performing authentication) have completed before continuing the evaluation of a route.
The method signatures for route functions in synchronous and asynchronous
evaluation are different: async route functions take an additional next()
callback.
Synchronous route functions
var router = ;router;
Asynchronous route functions
var router = ;router;
Resources
Available on the Client-side only. An object literal containing functions. If a host object is specified, your route definitions can provide string literals that represent the function names inside the host object. A host object can provide the means for better encapsulation and design.
var router =;var container ={ return true; }{ return true; };
History API
Available on the Client-side only. Director supports using HTML5 History
API instead of hash fragments for navigation. To use the API, pass
{html5history: true}
to configure()
. Use of the API is enabled only if the
client supports pushState()
.
Using the API gives you cleaner URIs but they come with a cost. Unlike with hash fragments your route URIs must exist. When the client enters a page, say http://foo.com/bar/baz, the web server must respond with something meaningful. Usually this means that your web server checks the URI points to something that, in a sense, exists, and then serves the client the JavaScript application.
If you're after a single-page application you can not use plain old <a href="/bar/baz">
tags for navigation anymore. When such link is clicked, web
browsers try to ask for the resource from server which is not of course desired
for a single-page application. Instead you need to use e.g. click handlers and
call the setRoute()
method yourself.
this
Attach Properties To Available in the http router only. Generally, the this
object bound to
route handlers, will contain the request in this.req
and the response in
this.res
. One may attach additional properties to this
with the
router.attach
method:
var director = ; var router = ; // // Attach properties to `this` // router; // // Access properties attached to `this` in your routes! // router;
This API may be used to attach convenience methods to the this
context of
route handlers.
HTTP Streaming and Body Parsing
When you are performing HTTP routing there are two common scenarios:
- Buffer the request body and parse it according to the
Content-Type
header (usuallyapplication/json
orapplication/x-www-form-urlencoded
). - Stream the request body by manually calling
.pipe
or listening to thedata
andend
events.
By default director.http.Router()
will attempt to parse either the .chunks
or .body
properties set on the request parameter passed to
router.dispatch(request, response, callback)
. The router instance will also
wait for the end
event before firing any routes.
Default Behavior
var director = ;var router = ;router;
In flatiron, director
is used in conjunction with union which uses
a BufferedStream
proxy to the raw http.Request
instance. union will
set the req.chunks
property for you and director will automatically parse the
body. If you wish to perform this buffering yourself directly with director
you can use a simple request handler in your http server:
var http =director = ;var router = ;var server = http;router;
Streaming Support
If you wish to get access to the request stream before the end
event is
fired, you can pass the { stream: true }
options to the route.
var director = ;var router = ;router;
Instance methods
configure(options)
options
{Object}: Options to configure this instance with.
Configures the Router instance with the specified options
. See
Configuration for more documentation.
param(token, matcher)
- token {string}: Named parameter token to set to the specified
matcher
- matcher {string|Regexp}: Matcher for the specified
token
.
Adds a route fragment for the given string token
to the specified regex
matcher
to this Router instance. See URL Parameters for more
documentation.
on(method, path, route)
method
{string}: Method to insert within the Routing Table (e.g.on
,get
, etc.).path
{string}: Path within the Routing Table to set theroute
to.route
{function|Array}: Route handler to invoke for themethod
andpath
.
Adds the route
handler for the specified method
and path
within the
Routing Table.
path(path, routesFn)
path
{string|Regexp}: Scope within the Routing Table to invoke theroutesFn
within.routesFn
{function}: Adhoc Routing function with calls tothis.on()
,this.get()
etc.
Invokes the routesFn
within the scope of the specified path
for this Router
instance.
dispatch(method, path[, callback])
- method {string}: Method to invoke handlers for within the Routing Table
- path {string}: Path within the Routing Table to match
- callback {function}: Invoked once all route handlers have been called.
Dispatches the route handlers matched within the Routing Table
for this instance for the specified method
and path
.
mount(routes, path)
- routes {object}: Partial routing table to insert into this instance.
- path {string|Regexp}: Path within the Routing Table to insert the
routes
into.
Inserts the partial Routing Table, routes
, into the Routing
Table for this Router instance at the specified path
.
Instance methods (Client-side only)
init([redirect])
redirect
{String}: This value will be used if '/#/' is not found in the URL. (e.g., init('/') will resolve to '/#/', init('foo') will resolve to '/#foo').
Initialize the router, start listening for changes to the URL.
getRoute([index])
index
{Number}: The hash value is divided by forward slashes, each section then has an index, if this is provided, only that section of the route will be returned.
Returns the entire route or just a section of it.
setRoute(route)
route
{String}: Supply a route value, such ashome/stats
.
Set the current route.
setRoute(start, length)
start
{Number} - The position at which to start removing items.length
{Number} - The number of items to remove from the route.
Remove a segment from the current route.
setRoute(index, value)
index
{Number} - The hash value is divided by forward slashes, each section then has an index.value
{String} - The new value to assign the the position indicated by the first parameter.
Set a segment of the current route.
Frequently Asked Questions
What About SEO?
Is using a Client-side router a problem for SEO? Yes. If advertising is a requirement, you are probably building a "Web Page" and not a "Web Application". Director on the client is meant for script-heavy Web Applications.