百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

director

> 编程语言
开源

一个小而同构的 URL 路由器,用于 JavaScript

5.6K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

一个小而同构的 URL 路由器,用于 JavaScript

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

  • Client-Side Routing
  • Server-Side HTTP Routing
  • Server-Side CLI Routing

Usage

  • API Documentation
  • Frequently Asked Questions

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:

…

Director works great with your favorite DOM library, such as jQuery.

…

You can find a browser-specific build of director [here][1] which has all of the server code stripped away.

Server-Side HTTP Routing

Director handles routing for HTTP requests similar to journey or express:

…

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 = require('director');

  var router = new director.cli.Router();

  router.on('create', function () {
    console.log('create something');
  });

  router.on(/destroy/, function () {
    console.log('destroy something');
  });

  // You will need to dispatch the cli arguments yourself
  router.dispatch('on', process.argv.slice(2).join(' '));

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 create
create something
$ node foo.js destroy
destroy 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 = Router(routes);

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 = Router(routes);

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 = new Router().init();

  router.on('/some/resource', function () {
    //
    // Do something on `/#/some/resource`
    //
  });

HTTP Routing

  var router = new director.http.Router();

  router.get(/\/some\/resource/, function () {
    //
    // Do something on an GET to `/some/resource`
    //
  });

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:

…

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 = new director.Router(routes).configure(options);

The options are:

  • recurse: Controls route recursion. Use forward, backward, or false. Default is false Client-side, and backward Server-side.
  • strict: If set to false, then trailing slashes (or other delimiters) are allowed in routes. Default is true.
  • async: Controls async routing. Use true or false. Default is false.
  • 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 supports pushState(), 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 upon Router.init() since with real URIs the router can not know if it should call a route handler or not. Setting this to false 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 upon Router.init() since with canonical URIs the router can not know if it should convert the hash to a route or not. Setting this to false disables the hash conversion on router initialisation.

URL Matching

  var router = Router({
    //
    // given the route '/dog/yella'.
    //
    '/dog': {
      '/:color': {
        //
        // this function will return the value 'yella'.
        //
        on: function (color) { console.log(color) }
      }
    }
  });

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 = Router({
    //
    // given the route '/hello/world'.
    //
    '/hello': {
      '/(\\w+)': {
        //
        // this function will return the value 'world'.
        //
        on: function (who) { console.log(who) }
      }
    }
  });
  var router = Router({
    //
    // given the route '/hello/world/johny/appleseed'.
    //
    '/hello': {
      '/world/?([^\/]*)\/([^\/]*)/?': function (a, b) {
        console.log(a, b);
      }
    }
  });

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 = new director.Router();

  //
  // A route could be defined using the `userId` explicitly.
  //
  router.on(/([\w-_]+)/, function (userId) { });

  //
  // Define a shorthand for this fragment called `userId`.
  //
  router.param('userId', /([\\w\\-]+)/);

  //
  // Now multiple routes can be defined with the same
  // regular expression.
  //
  router.on('/anything/:userId', function (userId) { });
  router.on('/something-else/:userId', function (userId) { });

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.on("/foo/?((\w|.)*)"), function (path) { });

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: growl
      },
      on: bark
    }
  };

  var router = Router(routes);

Recursion set to backward, with the URL /dog/angry

  var routes = {
    '/dog': {
      '/angry': {
        //
        // This method will be fired first.
        //
        on: growl
      },
      //
      // This method will be fired second.
      //
      on: bark
    }
  };

  var router = Router(routes).configure({ recurse: 'backward' });

Recursion set to forward, with the URL /dog/angry

  var routes = {
    '/dog': {
      '/angry': {
        //
        // This method will be fired second.
        //
        on: growl
      },
      //
      // This method will be fired first.
      //
      on: bark
    }
  };

  var router = Router(routes).configure({ recurse: 'forward' });

Breaking out of recursion, with the URL /dog/angry

  var routes = {
    '/dog': {
      '/angry': {
        //
        // This method will be fired first.
        //
        on: function() { return false; }
      },
      //
      // This method will not be fired.
      //
      on: bark
    }
  };

  //
  // This feature works in reverse with recursion set to true.
  //
  var router = Router(routes).configure({ recurse: 'backward' });

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 evalua

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

JavaScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言