View on GitHub

Lennon.js

A Javascript router

Download this project as a .zip file Download this project as a tar.gz file

Why?

Why another JS router you may ask? Well, I was in need of an extremely lightweight router, that would take advantage of the History API and fallback to hash. Most of the routers I came across, while wonderful projects in their own right, contained way more than I was looking for. The project I was working on was already using amplify.js, so I really just wanted to pass my router an event name to publish rather than a callback to run.

So, I wrote Lennon to do just that. Define a few routes and tell it which event to publish (you can optionally pass a callback, as well) then run!

In a nutshell,

var router = new Lennon();
router.define('/', 'myDefaultRoute');
router.define('/another/:route', 'anotherRoute');
router.process();

When process is called, the passed event name would be dispatched on the matching route. Granted, you have to pass a publish method to Lennon's constructor. If you aren't using pub/sub, callbacks work all the same.

var router = new Lennon();
router.define('/', function(context) {
    //-- Do default route stuff
});
router.define('/another/:route', function(context) {
    //-- Do stuff with context.route
});
router.process();

Dependencies

Modernizr, jQuery 1.8.6+

Constructor Options

Creating the Lennon object

var router = new Lennon({
    logger: myCustomLogger,
    publishEvent: somePubSubLibrary.publish
});

Defining routes

You can add dynamic route parameters by prefixing with a colon (/someModule/:id). The context object will then parse the path value into a property called id.

With callbacks

router.define('/', function(context) {
    //-- Do stuff
});

router.define('/some/:path', function(context) {
    /*
    This will match "/some/param" and context will be
    {Object} => {
        path: "param"
    }
    */
});

With pubsub

router.define('/', 'defaultPathEventName');
router.define('/some/:path', 'someOtherPathEventName');

somePubSubLibrary.subscribe('defaultPathEventName', function(context) {
    //-- Do stuff
});
somePubSubLibrary.subscribe('someOtherPathEventName', function(context) {
    /*
    This will match "/some/param" and context will be
    {Object} => {
        path: "param"
    }
    */
});

See it in action

Just a simple demo page to dynamically add routes and see how pushState or onhashchange responds to them. See it here.

Future stuff