Skip to content

Instantly share code, notes, and snippets.

@jackboberg
Forked from apcomplete/Backtrace.js
Last active December 23, 2015 22:29
Show Gist options
  • Save jackboberg/6703126 to your computer and use it in GitHub Desktop.
Save jackboberg/6703126 to your computer and use it in GitHub Desktop.
(function() {
Backtrace = {};
Backtrace.Router = (function() {
Router.prototype.optionalParam = /\((.*?)\)/g;
Router.prototype.namedParam = /:\w+/g;
Router.prototype.splatParam = /\*\w+/g;
Router.prototype.escapeRegExp = /[-{}[\]+?.,\\^$|#\s]/g;
Router.prototype.rootURL = "";
Router.prototype.routes = {
};
function Router() {
this.initialize.apply(this);
this.execRoute();
return this;
}
Router.prototype.initialize = function() {};
Router.prototype.routeToRegExp = function(route) {
route = route.replace(this.escapeRegExp, '\\$&').replace(this.optionalParam, '(?:$1)?').replace(this.namedParam, '([^\/]+)').replace(this.splatParam, '(.*?)');
return new RegExp('^' + route + '$');
};
Router.prototype.execRoute = function() {
var path, route, _results;
path = window.location.pathname.substring(this.rootURL.length+1);
_results = [];
for (route in this.routes) {
if (this.routeToRegExp(route).test(path)) {
var args = this._extractParameters(this.routeToRegExp(route), path);
this[this.routes[route]].apply(this,args);
}
}
};
Router.prototype._extractParameters = function(route, fragment) {
var params = route.exec(fragment).slice(1);
return _.map(params, function(param) {
return param ? decodeURIComponent(param) : null;
});
};
return Router;
})();
}).call(this);
// comment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment