Created
June 16, 2014 20:24
-
-
Save themasch/149fd71115e47706ccc2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Route = function(config) { | |
this.path = config.path || '' | |
var keys = [], | |
raws = {}, | |
regexp = new RegExp( | |
this.path.replace( | |
/{([a-zA-Z0-9_-]+)}/g, | |
function(full, name) { | |
raws[name] = full | |
keys.push(name) | |
return '([^/]+)' | |
} | |
) | |
) | |
this.keys = keys | |
this.raws = raws | |
this.pattern = regexp | |
this.controller = config.controller || function() { } | |
} | |
Route.prototype.match = function(string) { | |
var matches = string.match(this.pattern) | |
if(!matches) { | |
return false | |
} | |
if(matches.length !== this.keys.length + 1) { | |
return false | |
} | |
var params = {} | |
for(var i=0;i<this.keys.length;i++) { | |
params[this.keys[i]] = matches[i+1] | |
} | |
return params | |
} | |
Route.prototype.generate = function(options) { | |
var str = this.path | |
for(var key in this.raws) { | |
str = str.replace(this.raws[key], options[key]) | |
} | |
return str | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Router = function(config) { | |
this.routes = config.routes.map(this.createRoute) | |
} | |
Router.prototype.createRoute = function(config) { | |
return new Route(config) | |
} | |
Router.prototype.update = function() { | |
var hash = (window.location.hash || '').replace(/^#!/, '') | |
for(var i in this.routes) { | |
var route = this.routes[i] | |
var match = route.match(hash) | |
if(match) { | |
route.controller(match) | |
} | |
} | |
} | |
Router.prototype.url = function(name, params) { | |
for(var i=0;i<this.routes.length;i++) { | |
if(this.routes[i].name && this.routes[i].name === name) { | |
return this.routes[i].generate(params) | |
} | |
} | |
return false | |
} | |
Router.prototype.navTo = function(name, params) { | |
window.location.nav = '#!' + this.url(name, params) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment