Skip to content

Instantly share code, notes, and snippets.

@tipiirai
Created July 2, 2014 02:12
Show Gist options
  • Save tipiirai/a1f2d1f203de0b5f45a1 to your computer and use it in GitHub Desktop.
Save tipiirai/a1f2d1f203de0b5f45a1 to your computer and use it in GitHub Desktop.
Riot.js full router
(function() {
var routes = [];
function on(route, fn) {
var keys = ['match'];
route = route.replace(/[\/\=\?\$\^]/g, '\\$&').replace(/\{(\w+)\}/g, function(match, key) {
keys.push(key);
return '(\\w+)';
});
routes.push({ re: RegExp(route), keys: keys, fn: fn });
}
function emit(path) {
for (var i = 0, route, match; (route = routes[i]); i++) {
match = route.re.exec(path);
if (match) {
for (var j = 0, params = { path: path }, val; (val = match[j]); j++) {
params[route.keys[j]] = val;
}
route.fn(params);
}
}
}
riot.route = function(arg, fn) {
fn ? on(arg, fn) : typeof arg == 'function' ? on(".*", arg) : emit(arg);
return riot;
};
})();
@3den
Copy link

3den commented Jul 2, 2014

Besides those comments, It was cool that you used an array instead of an object for the routes that simplified a lot the only down side is because all routes will need to loop on the list there is no more O(1) in the best case scenario, but that is not an issue because the most routes will have params or wildcard.

@3den
Copy link

3den commented Jul 2, 2014

wow i noticed that issue 3 wont happen because you will match all routes... I really like that ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment