Created
October 15, 2011 01:04
-
-
Save bpierre/1288822 to your computer and use it in GitHub Desktop.
A simple routing function for jQuery history
This file contains hidden or 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
| // 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); |
This file contains hidden or 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
| 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