Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Last active December 27, 2018 04:37
Show Gist options
  • Save henriquegogo/916406 to your computer and use it in GitHub Desktop.
Save henriquegogo/916406 to your computer and use it in GitHub Desktop.
Easy routes with javascript and hash
(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