Created
November 4, 2011 05:07
-
-
Save gjohnson/1338703 to your computer and use it in GitHub Desktop.
Regex Hash Router
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
<a href="#/hello">hello</a> | |
<br/> | |
<a href="#/bye">bye</a> | |
<script> | |
route | |
(/^\/hello$/, function(){ alert('hello ran'); }) | |
(/^\/bye$/, function(){ alert('bye ran'); }) | |
; | |
</script> |
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
(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