Skip to content

Instantly share code, notes, and snippets.

@timrwood
Created May 18, 2012 17:53
Show Gist options
  • Save timrwood/2726713 to your computer and use it in GitHub Desktop.
Save timrwood/2726713 to your computer and use it in GitHub Desktop.
Routing roundup

Page.js

TJ Holowaychuk

~1.2k gzipped

http://visionmedia.github.com/page.js/

Started April 29 2012

Route support

Explicit paths, optional/required parameters, wildcard, regexp

"/user/"
"/user/:id"
"/user/:id/edit"
"/user/:id/:revision?"
"/download/(*)"
/^post\/\d{4}\/\d{2}\/\d{2}/

History.pushState

Opt out. No fallback for unsupported browsers.

page.start({
    popstate : false,
    click : false
});

May need some polyfill as it tries to use history.pushState even if it doesn't exist.

Multiple callbacks per route.

Shared context between callbacks.

page('/photos/:id', load, show);

function load(ctx, next) {
    $.getJSON('/photos/' + ctx.params.id + '.json', function(data){
        ctx.photo = data;
        next();
    });
}

function show(ctx) {
    $('img').attr('src', ctx.photo.url);
}

Fall-through callbacks

page('*', all);
page('/help/', help);

function all(ctx, next) {
    $.publish("new-page");
    next();
}

function help(ctx) {
    $('title').text('Help');
}

Crossroads.js

Miller Medeiros

~2k gzipped

http://millermedeiros.github.com/crossroads.js/

Route support

Explicit paths, optional/required parameters, wildcard, regexp

"/user/"
"/user/{id}"
"/user/{id}/edit"
"/user/{id}/:revision:"
"/download/:*:"
/^post\/\d{4}\/\d{2}\/\d{2}/

History.pushState

None. Would need to hook up seperately if desired.

Callbacks

Very verbose. Need to create route then bind to route separately.

var sectionRoute = crossroads.addRoute('/{section}/{id}');
function onSectionMatch(section, id){
    console.log(section +' - '+ id);
}
sectionRoute.matched.add(onSectionMatch);

Requires event library JS-Signals http://millermedeiros.github.com/js-signals/

Validation rules

var route = crossroads.addRoute('/{section}/{id}');
route.rules = {
    section : ['posts', 'photos'],
    id : function (value, request, values) {
        if (+value < 100) {
            return true;
        }
        return false;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment