Skip to content

Instantly share code, notes, and snippets.

@WA9ACE
Created September 18, 2016 19:00
Show Gist options
  • Save WA9ACE/8afd44bdc15e404ee6f3cf67f410860d to your computer and use it in GitHub Desktop.
Save WA9ACE/8afd44bdc15e404ee6f3cf67f410860d to your computer and use it in GitHub Desktop.
class Router {
constructor (routes = [], root = '/') {
this.routes = routes
this.root = root
window.addEventListener('hashchange', this._handler.bind(this))
}
start (initialRoute) {
this._handler()
}
navigate (path = '') {
if (this.mode === 'history') {
history.pushState(null, null, `${this.root}${this._clearSlashes(path)}`)
} else {
window.location.href = window.location.href.replace(/#(.*)$/, '') + '#' + path
}
}
add (path, handler) {
this.routes.push({
path,
handler
})
return this
}
_handler (event) {
const fragment = this._getFragment()
for (let i = 0; i < this.routes.length; i++) {
const route = this.routes[i]
if (route.path === '*') {
break
} else {
const match = fragment.match(route.path)
if (match) {
match.shift()
route.handler.apply({}, match)
return this
}
}
}
const catchAll = this.routes.find((route) => route.path === '*')
if (catchAll) {
catchAll.handler.apply({})
return this
}
}
_clearSlashes (path) {
return path.toString().replace(/\/$/, '').replace(/^\//, '')
}
_getFragment () {
let fragment = ''
if (this.mode === 'history') {
fragment = this._clearSlashes(decodeURI(location.pathname + location.search))
fragment = fragment.replace(/\?(.*)$/, '')
fragment = this.root != '/' ? fragment.replace(this.root, '') : fragment
} else {
const match = window.location.href.match(/#(.*)$/)
fragment = match ? match[1] : ''
}
return this._clearSlashes(fragment)
}
}
export default Router
@WA9ACE
Copy link
Author

WA9ACE commented Sep 18, 2016

Usage

let routes = [
  {
    path: 'contact',
    handler () {
      console.log('contact route')
    }
  }, {
    path: '*',
    handler () {
      console.log('default route')
    }
  }
]

let router = new Router(routes)
router.start()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment