Last active
December 22, 2021 08:45
-
-
Save ArturJS/9cc26c5821279f4b0348adf12ba7113f to your computer and use it in GitHub Desktop.
Js hash router
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({ | |
| pages, | |
| rootSelector | |
| }) { | |
| this.pages = pages; | |
| this.rootSelector = rootSelector; | |
| this.initRouting(); | |
| } | |
| findAndRenderPage = () => { | |
| const pageHash = location.hash.slice(1); | |
| const relatedPage = this.pages.find(page => page.hash === pageHash); | |
| if (!relatedPage) { | |
| location.hash = this.pages[0].hash; | |
| return; | |
| } | |
| const rootElement = document.querySelector(this.rootSelector); | |
| rootElement.innerHTML = relatedPage.render(); | |
| } | |
| initRouting() { | |
| window.addEventListener('hashchange', this.findAndRenderPage); | |
| this.findAndRenderPage(); | |
| } | |
| } | |
| const createRouter = () => new Router({ | |
| pages: [ | |
| { | |
| hash: 'window1', | |
| render() { | |
| return `<div> Page 1</div>` | |
| } | |
| } | |
| ], | |
| rootSelector: '#root' | |
| }); | |
| createRouter(); | |
| // in index.html add <div id="root"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment