Created
September 18, 2016 19:00
-
-
Save WA9ACE/8afd44bdc15e404ee6f3cf67f410860d 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage