-
Notifications
You must be signed in to change notification settings - Fork 1
/
router.js
54 lines (50 loc) · 1.68 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
// JavaScript router in 20 lines
// Joakim Carlstein - https://joakim.beng.se/
import { engine } from './engine';
let el = null;
let events = [];
const routes = {};
export const route = (path, templateId, controller) => {
const listeners = [];
controller.prototype.$on = (selector, evt, handler) => events.push([selector, evt, handler]);
controller.prototype.$refresh = () => listeners.forEach(fn => fn());
routes[path] = {
templateId: templateId,
controller: controller,
onRefresh: listeners.push.bind(listeners)
};
};
const forEachEvent = fnName => {
for (let i = 0; i < events.length; i++) {
const els = el.querySelectorAll(events[i][0]);
for (let j = 0; j < els.length; j++) {
els[j][fnName].apply(els[j], events[i].slice(1));
}
}
};
const router = () => {
// Lazy load view element:
el = el || document.getElementById('app');
// Remove current event listeners:
forEachEvent('removeEventListener');
// Clear events, to prepare for next render:
events = [];
// Current route url (getting rid of '#' in hash as well):
const url = location.hash.slice(1) || '/';
// Get route by url or fallback if it does not exist:
const route = routes[url] || routes['*'];
if (route && route.controller) {
const ctrl = new route.controller();
// Listen on route refreshes:
route.onRefresh(() => {
forEachEvent('removeEventListener');
// Render route template with John Resig's template engine:
el.innerHTML = engine(route.templateId, ctrl);
forEachEvent('addEventListener');
});
// Trigger the first refresh:
ctrl.$refresh();
}
};
window.addEventListener('hashchange', router);
window.addEventListener('load', router);