Skip to content

Instantly share code, notes, and snippets.

@JBreit
Created April 26, 2016 02:41
Show Gist options
  • Save JBreit/def60e30230cd417e78e941670e7e50a to your computer and use it in GitHub Desktop.
Save JBreit/def60e30230cd417e78e941670e7e50a to your computer and use it in GitHub Desktop.
var AddController = (function () {
'use strict';
var name = 'AddController';
function init() {
console.log('AddController');
}
return {
name: name,
init: init
};
}());
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Router Test</title>
</head>
<body>
<div id="app">
hello world
<a href="#list">List</a>
<a href="#add">Add</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="router.js"></script>
<script type="text/javascript">
App.Router.init();
</script>
</body>
</html>
var ListController = (function () {
'use strict';
var name = 'ListController';
function init() {
console.log('ListController');
}
return {
name: name,
init: init
};
}());
var App = App || {};
App.Router = (function () {
'use strict';
var name = 'SkyMap',
routes = [
{hash:'#list', controller:'ListController'},
{hash:'#add', controller:'AddController'}
],
defaultRoute = '/',
currentHash = '';
function getHash() {
console.log('This is where the code to get the document location hash');
}
function init() {
window.location.hash = window.location.hash || defaultRoute;
setInterval(hashCheck, 100);
console.log(this);
console.log('Router.init was triggered');
}
function hashCheck() {
var i = 0,
currentRoute;
if (window.location.hash !== currentHash){
for (; i < routes.length; i++) {
//console.log(routes[i]);
var currentRoute = routes[i];
if (window.location.hash === currentRoute.hash) {
loadController(currentRoute.controller);
//console.log(currentRoute.controller);
}
}
currentHash = window.location.hash;
console.log(currentHash);
console.log(currentRoute.controller);
}
}
function loadController(controllerName) {
$.ajax({
url: 'controllers/' + controllerName + '.js',
dataType: 'script',
cache: true
}).done(function (controller) {
console.log('Success loading ' + controllerName);
controller.init();
}).fail(function (controller) {
console.log('Failed to load ' + controllerName);
});
}
return {
init: init
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment