Skip to content

Instantly share code, notes, and snippets.

@wfaler
Created August 3, 2015 23:04
Show Gist options
  • Save wfaler/80b495e25cb4df733920 to your computer and use it in GitHub Desktop.
Save wfaler/80b495e25cb4df733920 to your computer and use it in GitHub Desktop.
A Javascript router in 83 LOCS (including white space).
var Router = function(routeDef){
this.routes = [];
routeDef.call(this);
};
Router.prototype.splitPath = function(path){
var splits = path.split('/');
return _.filter(splits, function(part){
return part !== '';
});
};
Router.prototype.hashLocation = function(){
var hash = window.location.hash;
var index = hash.indexOf('#/');
if(hash === '#/'){
return [];
}else if(index >= 0){
hash = hash.substring(index + 2, hash.length);
return this.splitPath(hash);
}else{
return [];
}
};
Router.prototype.findRoute = function(path){
var self = this;
var matchPart = function(pathPart, routePart){
if(routePart.indexOf(':') === 0){
self.params[routePart.substring(1)] = pathPart;
return true;
}else{
return routePart === pathPart;
}
};
if(path.length === 0){
return _.find(this.routes, function(r){
return r.path.length === 0;
});
}else{
var candidates = _.filter(this.routes, function(r){
return r.path.length === path.length;
});
return _.find(candidates,function(route){
var match = true;
for(var i = 0; i < path.length;i++){
if(match){
match = matchPart(path[i],route.path[i]);
}
}
return match;
});
}
};
Router.prototype.runRoute = function(path){
this.params = {};
var routeDef = this.findRoute(path);
if(!_.isUndefined(routeDef)){
routeDef.handler.call(this);
}
};
Router.prototype.run = function(){
var self = this;
$(window).bind('hashchange', function() {
self.runRoute(self.hashLocation());
});
if(window.location.hash === ''){
window.location = window.location + '#/';
}
self.runRoute(self.hashLocation());
};
Router.prototype.get = function(path, handler){
this.routes.push({path: this.splitPath(path), handler: handler});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment