Last active
December 27, 2018 04:37
-
-
Save henriquegogo/916406 to your computer and use it in GitHub Desktop.
Easy routes with javascript and hash
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
(function() { | |
var Router = function(routes) { | |
var hash; | |
var splitParams = function() { | |
for (route in routes) { | |
var routeRegex = "^" + route.replace(/:([A-z0-9_-]*)/g, "([A-z0-9_-]*)") + "(/?)$"; | |
var callRoute = routes[route]; | |
var matches = new RegExp(routeRegex).exec(hash); | |
if (matches) { | |
matches.shift(); | |
callRoute.apply(this, matches); | |
break; | |
} | |
} | |
}; | |
var checkHash = function() { | |
if (window.location.hash != hash) { | |
hash = window.location.hash; | |
splitParams(); | |
} | |
}; | |
if ('onhashchange' in window) { | |
window.addEventListener('hashchange', checkHash); | |
} else { | |
window.setInterval(checkHash, 200); | |
} | |
if (!window.location.hash) { | |
window.location.hash = "#/"; | |
} | |
checkHash(); | |
}; | |
var controller = new Router({ | |
"#/": function() { | |
console.log('start'); | |
}, | |
"#/user/:id": function(id) { | |
console.log("Opening", id); | |
}, | |
"#/user/:id/edit": function(id) { | |
console.log("Editing", id); | |
}, | |
"#/user/:id/:curriculum": function(id, curriculum) { | |
console.log("Editing " + id + " with curriculum " + curriculum); | |
}, | |
"#/help": function() { | |
console.log('help'); | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment