Created
September 4, 2014 13:06
-
-
Save miroli/15382d2f6822e3c9a626 to your computer and use it in GitHub Desktop.
Super Simple JavaScript Router
This file contains 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
var Router = { | |
routes: [], | |
route: '', | |
getFragment: function() { | |
return location.hash.replace('#',''); | |
}, | |
add: function(path, handler) { | |
this.routes.push({ path: path, handler: handler }); | |
}, | |
remove: function(path) { | |
var r = this.routes, i; | |
for (i = 0; i < r.length; i++) { | |
if (r[i].path === path) { | |
r.pop(r[i]); | |
} | |
} | |
}, | |
listen: function() { | |
var self = this; | |
self.route = self.getFragment(); | |
var fn = function() { | |
if (self.route !== self.getFragment()) { | |
self.route = self.getFragment(); | |
self.execute(); | |
} | |
}; | |
setInterval(fn, 50); | |
}, | |
execute: function() { | |
var r = this.routes, route = this.route, i; | |
for (i = 0; i < r.length; i++) { | |
if (r[i].path === route) { | |
r[i].handler.call({}, route); | |
} | |
} | |
}, | |
navigate: function(path) { | |
location.hash = path; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment