Skip to content

Instantly share code, notes, and snippets.

@russellbeattie
Last active June 12, 2018 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save russellbeattie/8adae3f5a6f459200fc491d9bebe5a95 to your computer and use it in GitHub Desktop.
Save russellbeattie/8adae3f5a6f459200fc491d9bebe5a95 to your computer and use it in GitHub Desktop.
export default class Router {
constructor(){
this.routes = [];
this.current = null;
}
add(route, handler) {
let re = new RegExp(route + '$');
if(route === ''){
re = /^\s*$/;
}
this.routes.push({ re: re, handler: handler});
}
navigate(path = '') {
window.location.href = window.location.href.replace(/#(.*)$/, '') + '#' + path;
}
start() {
window.addEventListener('hashchange', this.processRoutes.bind(this));
this.processRoutes();
this.start = function(){};
}
processRoutes(){
let hashMatch = window.location.href.match(/#(.*)$/);
let newPath = hashMatch ? hashMatch[1] : '';
newPath.toString().replace(/\/$/, '').replace(/^\//, '');
if(this.current !== newPath) {
this.current = newPath;
for(let i = 0; i < this.routes.length; i++) {
let routeMatch = this.current.match(this.routes[i].re);
if(routeMatch) {
routeMatch.shift();
this.routes[i].handler.apply({}, routeMatch);
return;
}
}
}
}
}
//
import Router from './router.js';
var router = new Router();
router.add('', root);
router.add('home', home);
router.add('test', test);
router.add('test/(.*)', test2);
router.add('.*', notFound);
var content = document.querySelector('.content');
router.start();
function root(){
router.navigate('home');
}
function home(){
content.innerHTML = '<h1>Home</h1>';
}
function test(){
content.innerHTML = '<h1>Test</h1>';
}
function test2(val){
console.log(val);
content.innerHTML = '<h1>' + val + '</h1>';
}
function notFound(){
content.innerHTML = '<h1>Not Found</h1>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment