-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathhistoryRouter.js
52 lines (45 loc) · 1.11 KB
/
historyRouter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// HistoryRouter similar with HashRouter
class HistoryRouter { // eslint-disable-line no-unused-vars
constructor() {
this.routers = {};
/**
* invoke this.init method, init event listener
*/
this.init();
}
init = () => {
/**
* invoke this.wrapALink()
*/
this.wrapALink();
window.addEventListener('popstate', this.updateView, false);
window.addEventListener('load', this.updateView, false);
}
/**
* wrap a link prevent event default
*/
wrapALink = () => {
const me = this;
const links = document.links;
for (let i = 0; i < links.length; i++) {
const link = links[i];
link.addEventListener('click', function (e) {
e.preventDefault();
history.pushState(null, null, link.pathname);
me.updateView();
});
}
}
route = (path, callback) => {
if (!path || typeof path !== 'string') {
return;
}
this.routers[path] = callback || function () {};
}
updateView = () => {
const currentUrl = location.pathname;
if (this.routers[currentUrl]) {
this.routers[currentUrl]();
}
}
}