-
Notifications
You must be signed in to change notification settings - Fork 0
/
client-side-router.html
59 lines (48 loc) · 1.3 KB
/
client-side-router.html
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
59
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Router example</title>
</head>
<body>
<p>Try and replace me when the router runs!</p>
<script src="../dist/router.umd.js"></script>
<script>
router({
"/home": params => {
document.body.innerHTML = "HOMEPAGE";
console.log("HOME PAGE", params)
},
"/user/:userId/tab/:tabId": params => {
document.body.innerHTML = `Profile id: ${params.userId}, Tab: ${params.tabId}`;
console.log(`Profile userId: ${params.userId}`)
},
"/user/:userId": params => {
document.body.innerHTML = "PROFILE" + `<br><pre>${JSON.stringify(params)}</pre>`;
console.log("PROFILE PAGE", params)
}
})
// How to bind the router to URL changes in the browser:
// 1. capture link clicks for links such as <a href="#/profile/1">some text</a>
window.addEventListener(
"click",
function handleLink(e) {
if (!e.target.matches("a")) return
if (!e.target.href.matches(/^#/)) return
e.preventDefault()
location.hash = e.target.hash
},
false
)
// 2. monitor changes to window.location.hash,
// run the router when it changes
window.addEventListener(
"hashchange",
function(e) {
router.href(window.location.hash)
},
false
)
</script>
</body>
</html>