Passed
Push — master ( 71527a...9c3746 )
by Endre
47s queued 11s
created

Router.attachTo   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
import {IObserver} from '@enbock/state-value-observer/Observer';
2
3
export interface IPageData {
4
  name: string,
5
  baseUrl: string
6
  currentUrl: string
7
}
8
9 1
export default class Router {
10
  currentPage: IObserver<IPageData | null>;
11
  history: History;
12
13
  constructor(pageObserver: IObserver<IPageData | null>, history: History) {
14 5
    this.currentPage = pageObserver;
15 5
    this.history = history;
16
  }
17
18 1
  attachTo(window: Window) {
19 2
    window.addEventListener('popstate', this.onHistoryChange.bind(this));
20
  }
21
22 1
  initialize(): void {
23 2
    if (this.currentPage.value == null) return;
24 1
    const firstPage: IPageData = this.currentPage.value;
25 1
    this.history.replaceState(firstPage, firstPage.name, firstPage.baseUrl);
26 1
    this.updatePage(firstPage);
27
  }
28
29 1
  changePage(newPage: IPageData): void {
30 2
    const currentPage: IPageData | null = this.currentPage.value;
31 4
    if (currentPage != null && currentPage.name == newPage.name) {
32 1
      return;
33
    }
34
35 1
    this.history.replaceState(newPage, newPage.name, newPage.currentUrl);
36 1
    this.updatePage(newPage);
37
  }
38
39 1
  protected updatePage(page: IPageData): void {
40 3
    this.currentPage.value = page;
41
  }
42
43 1
  protected onHistoryChange(event: PopStateEvent): void {
44 1
    const newPage: IPageData = event.state as IPageData;
45 1
    this.updatePage(newPage);
46
  }
47
}
48