-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathhashRouter.js
44 lines (40 loc) · 991 Bytes
/
hashRouter.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
// hashRouter constructor
class HashRouter { // eslint-disable-line no-unused-vars
constructor() {
/**
* set this.routers map object, like:
* { '/about': () => any }
*/
this.routers = {};
/**
* invoke this.init method, init event listener
*/
this.init();
}
/**
* 1.listen window.load event
* 2.listen window.hashchange event
* 3.all bind to this.updateView method
*/
init = () => {
window.addEventListener('load', this.updateView, false);
window.addEventListener('hashchange', this.updateView, false);
}
/**
* get router path from window.location.hash
* excute path's callback
*/
updateView = () => {
const currentUrl = window.location.hash.slice(1);
this.routers[currentUrl] && this.routers[currentUrl]();
}
/**
* register router path and it's callback
*/
route = (path, callback) => {
if (!path) {
return;
}
this.routers[path] = callback || function () {};
}
}