Created
December 30, 2016 08:19
-
-
Save Lxxyx/f53fe7f1bdd6d3d572ed375cff39b627 to your computer and use it in GitHub Desktop.
SimpleRouter
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
interface IRoutes { | |
path: string, | |
content: string | |
} | |
class Router { | |
routes: Array<IRoutes> = [] | |
view: HTMLDivElement = null | |
register (route: IRoutes) :void { | |
this.routes.push(route) | |
} | |
getContent (path: string) :string { | |
let index = -1 | |
let content = '' | |
for (let route of this.routes) { | |
if (path === route.path) { | |
content = route.content | |
break | |
} | |
} | |
return content | |
} | |
matchPath () { | |
const path = location.hash.replace('#', '') | |
const content = this.getContent(path) | |
if (content) { | |
this.view.innerHTML = content | |
} else { | |
this.view.innerHTML = '' | |
} | |
} | |
start (selector: string) :void { | |
this.view = <HTMLDivElement>document.querySelector(selector) | |
window.addEventListener('hashchange', this.matchPath.bind(this), false) | |
this.matchPath() | |
} | |
} | |
const router = new Router() | |
router.register({ | |
path: '/hello', | |
content: '<h1>This is Hello</h1>' | |
}) | |
router.register({ | |
path: '/world', | |
content: '<h1>This is World</h1>' | |
}) | |
window.onload = () => { | |
router.start('#app') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment