Created
May 1, 2014 21:19
-
-
Save thure/57032cc0bba9cf3a1a04 to your computer and use it in GitHub Desktop.
A simple router that registers callbacks for popstate events.
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
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