Skip to content

Instantly share code, notes, and snippets.

@thure
Created May 1, 2014 21:19
Show Gist options
  • Save thure/57032cc0bba9cf3a1a04 to your computer and use it in GitHub Desktop.
Save thure/57032cc0bba9cf3a1a04 to your computer and use it in GitHub Desktop.
A simple router that registers callbacks for popstate events.
define(['underscore'], function(_) {
return new function() {
var self = this;
var routes = [];
var catchAllCallback = null;
this.addRoute = function(pattern, callback) {
routes.push({pattern: pattern, callback: callback});
};
this.catchAll = function(callback) {
catchAllCallback = callback;
};
this.route = function() {
var path = window.location.hash.substring(1);
var found = false;
_.each(routes, function(route) {
var matches = path.match(route.pattern);
if (matches) {
if (route.callback) {
route.callback.call(null, matches);
found = true;
}
}
});
if (!found && catchAllCallback)
catchAllCallback.call(null);
};
this.go = function(path) {
var currentURL = window.location.href;
currentURL = currentURL.replace(/#.*/, '') + '#' + path;
window.history.pushState(null, null, currentURL);
this.route();
};
window.onpopstate = this.route;
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment