Skip to content

Instantly share code, notes, and snippets.

@gjohnson
Created November 4, 2011 05:07
Show Gist options
  • Save gjohnson/1338703 to your computer and use it in GitHub Desktop.
Save gjohnson/1338703 to your computer and use it in GitHub Desktop.
Regex Hash Router
<a href="#/hello">hello</a>
<br/>
<a href="#/bye">bye</a>
<script>
route
(/^\/hello$/, function(){ alert('hello ran'); })
(/^\/bye$/, function(){ alert('bye ran'); })
;
</script>
(function(global){
var routes = [];
global.route = function(pattern, callback, context) {
var key;
var patternType = Object.prototype.toString.call(pattern);
context = context || null;
if (patternType === '[object String]') {
pattern = new RegExp(pattern);
}
routes.push({ pattern: pattern, callback: callback, context: context });
return route;
};
global.addEventListener('hashchange', function(e) {
var hash = location.hash.replace('#', '');
var len = routes.length;
var item;
var i;
for (i = 0; i < len; i++) {
item = routes[i];
if (item.pattern.test(hash)) {
item.callback.call(item.context);
}
}
}, false);
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment