Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple routing function for jQuery history
// Use it with jQuery history: http://tkyk.github.com/jquery-history-plugin/
// Hashes should begin with #!/ (see hash.slice(2) below)
(function($) {
$.history.initRoutes = function (routes) {
$(function() {
$.history.init(function(hash) {
hash = hash.slice(2);
var routeFound = false;
for (var rpath in routes) {
if (routes.hasOwnProperty(rpath)) {
var re = new RegExp(rpath);
var matched = hash.match(re);
if (matched) {
routes[rpath](matched.slice(1)); // Pass the matched result
routeFound = true;
break;
}
}
}
// No route found
if (!routeFound && routes['^404$']) routes['^404$']();
}, { unescape: "/" });
});
};
})(jQuery);
var routes = {};
// Do something for #!/
routes['^$'] = function() {
loadHome();
};
// Captures #!/article_by_name/my-article
routes['^article_by_name\\/([a-z0-9\-]+)$'] = function(args) {
loadArticleByName(args[0]);
};
// Captures #!/article_by_id_with_name/11-my-article
routes['^article_by_id_with_name\\/([0-9]+)\-[a-z0-9\-]*$'] = function(args) {
loadArticleByIdWithName(args[0]);
};
// Captures #!/category/12-my-category/page/2
routes['^category\\/(([0-9]+)[a-z0-9\-]*)/page/([0-9]+)$'] = function(args) {
loadCategoryPage(args[0], args[1]);
};
// No route found
routes['^404$'] = function() {
loadHome();
}
initRoutes(routes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment