Last active
September 7, 2015 09:56
-
-
Save doublejosh/d7c3d3027a1c2c0afa38 to your computer and use it in GitHub Desktop.
Simple JS application router
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
| /** | |
| * Application URL router. | |
| */ | |
| define(function (require) { | |
| function Router() { | |
| this.parser = {}; | |
| this.routes = []; | |
| /** | |
| * Carefully call route and pass arguments. | |
| * | |
| * @param {string} route | |
| */ | |
| function _try_route() { | |
| var body = document.querySelector('body'), | |
| pathList, | |
| route; | |
| // Discover URL. | |
| window.Router.parser.href = location.href; | |
| pathList = window.Router.parser.hash.split('/', 25); | |
| // Determine main route. | |
| route = pathList.shift(); | |
| route = (route) ? route.replace(/^#/, '') : 'default'; | |
| // Try router method. | |
| if (typeof window.Router.routes[route] === 'function') { | |
| window.Router.routes[route](pathList); | |
| // Update body class. | |
| body.className = body.className.replace(/\bscreen-[a-z|0-9]+\b/, 'screen-' + route); | |
| } | |
| else { | |
| console.log('Invalid route: ' + route); | |
| } | |
| } | |
| /** | |
| * Internal goto method. | |
| * | |
| * @param {array} pathList | |
| */ | |
| this.go = function go(pathList) { | |
| location.href = '#' + pathList.join('/'); | |
| _try_route(); | |
| }; | |
| /** | |
| * Page load or receive a URL change. | |
| * | |
| * @param {object} router | |
| */ | |
| this.init = function init(routes, listen) { | |
| this.parser = document.createElement('a'); | |
| this.routes = routes; | |
| _try_route(); | |
| // If monitoring for changes. | |
| if (listen) { | |
| if ('onhashchange' in window) { | |
| window.onhashchange = function hashChanged() { | |
| _try_route(); | |
| }; | |
| } | |
| else { | |
| alert("Your browser is not supported!"); | |
| } | |
| } | |
| }; | |
| } | |
| return Router; | |
| }); | |
| /************************* | |
| * main.js | |
| */ | |
| requirejs([ | |
| 'app/main', | |
| 'app/router' | |
| ], function(myApp, Router) { | |
| window.Router = new Router(); | |
| window.Router.init({ | |
| 'default': function welcome() { | |
| myApp.displayWelcome(); | |
| myApp.setLocation(); | |
| }, | |
| 'watch': myApp.playVideo(args), | |
| 'thing': function add(args) { | |
| myApp.doTheThing(args[0], args[1]); | |
| myApp.showForm(args[1]); | |
| } | |
| 'all': function all() { | |
| myApp.authUser(); | |
| } | |
| }, true); | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Allows for...
...little strange to use fragments as folders, but it's javascript!