Last active
April 18, 2020 05:19
-
-
Save mnikn/c5c47e6b8d01cb330c284e89b503aafc to your computer and use it in GitHub Desktop.
[router] a simple web router #utils
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
// the router should be sigleton | |
class Router { | |
constructor(routeMap) { | |
this._routeMap = routeMap; | |
this.bindEvent(); | |
} | |
init(url) { | |
let fn = this._routeMap[url]; | |
window.history.replaceState({url: url}, '', url); | |
if (fn) fn(); | |
let navElements = document.querySelectorAll('a'); | |
navElements.forEach(ele => ele.addEventListener('click', (e) => { | |
e.preventDefault(); | |
router.navigate(e.target.getAttribute('href')); | |
})); | |
} | |
navigate(url) { | |
let fn = this._routeMap[url]; | |
window.history.pushState({url: url}, '', url); | |
if (fn) fn(); | |
let navElements = document.querySelectorAll('a'); | |
navElements.forEach(ele => ele.addEventListener('click', (e) => { | |
e.preventDefault(); | |
router.navigate(e.target.getAttribute('href')); | |
})); | |
} | |
bindEvent() { | |
window.addEventListener('popstate', (obj) => { | |
if (!obj.state && !obj.state instanceof Object) return; | |
let url = obj.state.url; | |
this.navigate(url); | |
}); | |
} | |
} | |
let routeMap = { | |
'/home': () => { | |
document.body.innerHTML = '<div>home<br><a href="/error">error</a><br><a href="/happy">happy</a></div>'; | |
}, | |
'/error': () => { | |
document.body.innerHTML = '<div>error</div>'; | |
}, | |
'/happy': () => { | |
document.body.innerHTML = '<div>happy</div>'; | |
} | |
}; | |
let router = new Router(routeMap); | |
router.init(location.pathname); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment