Skip to content

Instantly share code, notes, and snippets.

@shashankduhan
Created January 2, 2017 01:22
Show Gist options
  • Select an option

  • Save shashankduhan/f414e87cc009f5f31fde1faa48085204 to your computer and use it in GitHub Desktop.

Select an option

Save shashankduhan/f414e87cc009f5f31fde1faa48085204 to your computer and use it in GitHub Desktop.
A simple Hash Router for javascript
//Shashank Duhan 2017 | CC.0
//You gonna need reflex.js for this :
// https://gist.github.com/shashankduhan/673a4e1223afe550ca69958bcb73181c
window.router = (()=>{
"use strict"
return {
state: 0,
init: function(user){
router.routes = router.state;
window.addEventListener("hashchange", router.router);
window.reflexes.linkedlist.push(window.router.reflexes);
router.router();
},
router: function(){
router.state = router.routes;
router.url = location.hash.slice(1) || '/';
if(router.url != "/"){
router.routes = router.url.split("/");
}else{
router.routes = [];
}
window.reflexes.dispatcher({id: "hashchanged"});
},
reflexes: function(e){
if(e.id == "hashchanged"){
log(router.routes);
if(window.router.routes.length == 0){
window.reflexes.dispatcher({id:"greet"});
}else if(window.router.routes.length == 1){
if(router.routes[0] == "home" || router.routes[0] == "dashboard"){
window.reflexes.dispatcher({id:"adminpage"});
}else{
//You can add more redirects else you can see 404 msg.
window.reflexes.dispatcher({id:"404"});
}
}
}
},
routeTo: x =>{
window.location.hash = x;
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment