-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
71 lines (63 loc) · 1.36 KB
/
index.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
69
70
71
var assert = require('assert');
var EventBus = require('./events');
var StateMap = require('./state');
// When the statemap is mutated, frame runs and
// the app is re-drawn.
function makeApp(initial={}) {
var app;
var rootEl;
var routes = [];
var bus = new EventBus();
var emit = bus.emit.bind(bus);
var state = new StateMap(initial, emit);
var onChangeState;
return (app = {
state,
routes,
update,
on,
emit,
mount: (el) => {
rootEl = el;
// console.log('mount', rootEl, app);
on('change', () => {
frame(app);
})
frame(app);
emit('load');
},
route: (tester, route) => {
routes.push([tester, route]);
}
})
function on(evName, fn) {
return bus.on(evName, () => fn(state, update))
}
function update(newState) {
for([key, updatedVal] of Object.entries(newState)) {
state[key] = updatedVal;
}
}
function findRoute() {
for(let [test, route] of routes) {
if(test(state)) {
return route;
}
}
}
function frame() {
var route = findRoute();
assert(route, 'found no route for state');
// run the route with the current data (state)
// and an emitter function for the state to
// emit events on.
route(state, emit)
// .then(toHtmlStream)
// .then(appendNodes)
.then(result => {
// TODO: Update the dom tree more graciously
rootEl.innerHTML = result;
});
}
}
module.exports = makeApp;