Last active
June 12, 2018 00:44
-
-
Save russellbeattie/8adae3f5a6f459200fc491d9bebe5a95 to your computer and use it in GitHub Desktop.
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
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