Simple router to bind URL paths to callback functions
JavaScript
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
dist
src
test
.babelrc
.editorconfig
.eslintrc
.gitattributes
.gitignore
.travis.yml
README.md
UNLICENSE
gulpfile.babel.js
package.json

README.md

Router

GitHub version Build Status Size

Simple router to bind URL paths to callback functions

Usage

var router = Router()
    .route('/', function(){
        // Handle home page 
    })
    .route('/posts', function(){
        // Handle posts
    })
    .route('/post/:id', function(id){
        // Handle single post with `id` provided as a parameter
    });

// Dispatch the router when the history is changed
window.addEventListener('popstate', router.dispatch.bind(router), false);

API

Router([routes])

Create a new 'Router' instance with or without the new operator. Optionally pass an object of routes that map the path to the callback function.

// Create a `Router` instance with routes
var router = Router({
    '/foo': function(){
        // Do something 
    },
    '/bar/:id': function(id){
        // Do something 
    }
});

Router#route(path, fn)

Add a new route to the router with a path which may or may not contain embedded parameters from which to extract from a matching URL and pass to the provided callback function. Returns the router instance for method chaining.

router.route('/foo/:bar/:baz', function(bar, baz){
    // Do something 
});

Router#dispatch([path])

Test a URL against all the routes and invoke the callback function of the first matching pattern, passing all if any parameters. If no path is given, the current window's URL path (location.pathname) is used. Returns the router instance for method chaining.

// Dispatch a path
router.dispatch('/foo');

// Dispatch using the window's current URL path
router.dispatch();

Installation

Router is CommonJS and AMD compatible with no dependencies. You can download the development or minified version, or install it in one of the following ways:

npm install ryanmorr/router

bower install ryanmorr/router

Tests

Run unit tests by issuing the following commands:

npm install
npm install -g gulp
gulp test

License

This project is dedicated to the public domain as described by the Unlicense.