Skip to content

Instantly share code, notes, and snippets.

@henriquegogo henriquegogo/easyRoutes.js
Last active Dec 27, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.