-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
54 lines (51 loc) · 1.84 KB
/
router.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
'use strict';
function Router(routes) {
this.routes = routes;
const that = this;
this.rootElem = document.getElementById('content');
this.hasChanged = function() {
var r = this.routes;
if (window.location.hash.length > 0) {
for (var i = 0, length = r.length; i < length; i++) {
var route = r[i];
if (route.isActiveRoute(window.location.hash.substr(1))) {
this.goToRoute(route.htmlName, route.linkTitle);
}
}
} else {
for (var i = 0, length = r.length; i < length; i++) {
var route = r[i];
if (route.default) {
this.goToRoute(route.htmlName, route.linkTitle);
}
}
}
}
this.goToRoute = function(htmlName, linkTitle) {
var url = htmlName,
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
// Add this:
// Put content received from the server into container <main>:
document.querySelector('main').innerHTML = this.responseText;
document.title = linkTitle;
}
};
xhttp.open('GET', url + '?t=' + Date.now(), true);
xhttp.send();
};
this.addRoutes = function(newRoutes) {
newRoutes.forEach(function(newRoute, idx) {
let found = false;
that.routes.forEach(function(route) {
if (route.htmlName == newRoute.htmlName) found = true;
});
if (!found) that.routes.push(newRoute);
});
};
window.addEventListener('hashchange', function(e) {
that.hasChanged();
});
that.hasChanged();
};