Skip to content

Instantly share code, notes, and snippets.

@Lxxyx
Created December 30, 2016 08:19
Show Gist options
  • Save Lxxyx/f53fe7f1bdd6d3d572ed375cff39b627 to your computer and use it in GitHub Desktop.
Save Lxxyx/f53fe7f1bdd6d3d572ed375cff39b627 to your computer and use it in GitHub Desktop.
SimpleRouter
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