-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter-elements.js
58 lines (41 loc) · 1.27 KB
/
router-elements.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
53
54
55
56
57
58
customElements.define('router-link', class extends HTMLAnchorElement {
constructor() {
super();
this.href = "#" + this.getAttribute('href');
}
}, {extends: "a"});
customElements.define('router-outlet', class extends HTMLElement {
#config = {
router: []
};
get router() {
return this.#config.router;
}
connectedCallback() {
if (this.hasAttribute('config')) {
let config = this.getAttribute('config');
try {
config = JSON.parse(config); // JSON
} catch (e) {
config = window[config]; // Global variable
}
this.#config = config;
}
window.addEventListener('hashchange', this.routeChange.bind(this));
window.addEventListener('load', this.routeChange.bind(this), { once: true });
}
disconnectedCallback() {
window.removeEventListener('hashchange', this.routeChange.bind(this));
}
async routeChange(event) {
let path = location.hash.slice(1);
let dest = this.router.match(path);
if (dest) {
let params = dest.exec(path);
this.innerHTML = await dest.render(params);
}
}
constructor() {
super();
}
});