| Total Complexity | 5 |
| Total Lines | 32 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | import {IObserver} from '../Observer/Observer'; |
||
| 8 | |||
| 9 | export default class Router { |
||
| 10 | currentPage: IObserver<IPageData>; |
||
| 11 | history: History; |
||
| 12 | |||
| 13 | constructor(pageObserver: IObserver<IPageData>, history: History) { |
||
| 14 | this.currentPage = pageObserver; |
||
| 15 | this.history = history; |
||
| 16 | } |
||
| 17 | |||
| 18 | attachTo(window: Window) { |
||
| 19 | window.addEventListener('popstate', this.onHistoryChange.bind(this)); |
||
| 20 | } |
||
| 21 | |||
| 22 | changePage(newPage: IPageData): void { |
||
| 23 | const currentPage = this.currentPage.value; |
||
| 24 | if (currentPage.name == newPage.name) { |
||
| 25 | return; |
||
| 26 | } |
||
| 27 | |||
| 28 | this.history.pushState(newPage, newPage.name, newPage.url); |
||
| 29 | |||
| 30 | this.updatePage(newPage); |
||
| 31 | } |
||
| 32 | |||
| 33 | updatePage(page: IPageData): void { |
||
| 34 | this.currentPage.value = page; |
||
| 35 | } |
||
| 36 | |||
| 37 | onHistoryChange(event: PopStateEvent) { |
||
| 38 | const newPage: IPageData = event.state as IPageData; |
||
| 39 | this.updatePage(newPage); |
||
| 40 | } |
||
| 41 | } |