Skip to content

Instantly share code, notes, and snippets.

@positlabs
Last active December 29, 2015 09:29
Show Gist options
  • Save positlabs/7650870 to your computer and use it in GitHub Desktop.
Save positlabs/7650870 to your computer and use it in GitHub Desktop.
hash router
/**
@HashRouter: Singleton hash router object.
// define onroute function
HashRouter.onroute = function(hash){}
// start the router
HashRouter.start();
// prefixes all hash routes. / is default
HashRouter.hashPrefix = "/";
// manually trigger a route
HashRouter.go("hello");
// get the current route
HashRouter.getRoute(); // 'hello'
window.location.hash; // '#/hello'
*/
HashRouter = new (function () {
var prevLocation, history = [];
var _this = this;
this.hashPrefix = "/";
// @return the hash without the prefix
this.getRoute = function(){
return window.location.hash.slice(1 + _this.hashPrefix.length);
};
this.getHistory = function(){
return history.concat();
};
this.start = function () {
prevLocation = _this.getRoute();
// manually call this the first time around
this.onroute(prevLocation, []);
setInterval(function () {
var newLocation = _this.getRoute();
if (newLocation != prevLocation) {
history.unshift(prevLocation);
_this.onroute(newLocation, history);
prevLocation = newLocation;
}
}, 100);
};
this.onroute = function (hash) {
};
this.go = function (hash) {
window.location.hash = "#" + this.hashPrefix + hash;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment