-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.js
68 lines (59 loc) · 1.71 KB
/
ui.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
59
60
61
62
63
64
65
66
67
68
/**
* Front-end application for Saur.
*/
export default class UI {
constructor(context) {
this.require = context;
this.observer = new MutationObserver((records) => this.update(records));
this.changed = [];
}
/**
* All filenames in the `./components` dir.
*/
get files() {
return this.require.keys();
}
/**
* Require all components in `./components`.
*/
get components() {
return this.files.map((file) => this.require(file).default);
}
/**
* Run the application's `initialize()` call for the first time, and
* set up the observer for the root element.
*/
start(target) {
this.initialize(target);
this.observer.observe(target, { childList: true, subtree: true });
}
/**
* Initializes all components by finding their elements, instantiating
* them, and binding their events.
*/
initialize(target) {
this.components.forEach((Component) => {
const elements = target.querySelectorAll(Component.selector);
elements.forEach((element) => {
const component = new Component(element);
Object.entries(Component.events).forEach(([event, methods]) => {
methods.forEach((property) => {
const method = component[property];
const handler = method.bind(component);
element.addEventListener(event, handler);
});
});
});
});
this.changed = [...this.changed, ...this.observer.takeRecords()];
}
/**
* Run when the DOM changes at any point, and re-initializes
* components within the scope of the change.
*/
update(records) {
records.forEach(({ addedNodes }) => {
[...addedNodes].forEach((target) => this.initialize(target));
});
}
}