33 lines
820 B
JavaScript
33 lines
820 B
JavaScript
|
class SimpleRouter {
|
||
|
constructor(routes) {
|
||
|
this.routes = routes;
|
||
|
this.init();
|
||
|
}
|
||
|
|
||
|
init() {
|
||
|
// window.addEventListener('popstate', () => this.route());
|
||
|
// document.addEventListener('DOMContentLoaded', () => this.route());
|
||
|
// document.addEventListener('click', (e) => {
|
||
|
// if (e.target.tagName === 'A') {
|
||
|
// e.preventDefault();
|
||
|
// this.navigate(e.target.href);
|
||
|
// }
|
||
|
// });
|
||
|
this.route();
|
||
|
}
|
||
|
|
||
|
navigate(path) {
|
||
|
window.history.pushState({}, '', path);
|
||
|
this.route();
|
||
|
}
|
||
|
|
||
|
route() {
|
||
|
const path = window.location.pathname;
|
||
|
const route = this.routes[path] || this.routes['/404'];
|
||
|
if (route) {
|
||
|
route();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export {SimpleRouter}
|