Skip to content

Instantly share code, notes, and snippets.

@doublejosh
Last active September 7, 2015 09:56
Show Gist options
  • Select an option

  • Save doublejosh/d7c3d3027a1c2c0afa38 to your computer and use it in GitHub Desktop.

Select an option

Save doublejosh/d7c3d3027a1c2c0afa38 to your computer and use it in GitHub Desktop.
Simple JS application router
/**
* 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);
});
@doublejosh

Copy link
Copy Markdown
Author

Allows for...

<body class="screen-watch">
  <section class="screen default"></section>
  <section class="screen watch"></section>
  <section class="screen thing"></section>
.screen { display: none; }
.screen-watch .watch { display: block; }

...little strange to use fragments as folders, but it's javascript!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment