|
1 | | -import { destroyDOM } from './destroy-dom'; |
2 | | -import { mountDOM } from './mount-dom'; |
3 | | -import { Dispatcher } from './dispatcher'; |
4 | | -import { patchDOM } from './patch-dom'; |
| 1 | +import { mountDOM } from "./mount-dom"; |
| 2 | +import { destroyDOM } from './destroy-dom' |
| 3 | +import { hElement } from "./h"; |
5 | 4 |
|
6 | | -export function createApp({ state, view, reducers = {} }) { |
| 5 | +export function createApp(RootComponent, props = {}) { |
7 | 6 | let parentEl = null; |
8 | | - let vdom = null; |
9 | | - let isMounted = null; |
10 | | - |
11 | | - const dispatcher = new Dispatcher(); |
12 | | - // Subscribed the renderApp() function to be an after-command handler |
13 | | - // so that the application is re-rendered after every command is handled. |
14 | | - const subscriptions = [dispatcher.afterEveryCommand(renderApp)] |
15 | | - |
16 | | - function dispatchEvent(eventName, payload) { |
17 | | - dispatcher.dispatch(eventName, payload); |
18 | | - } |
19 | | - |
20 | | - for (const actionName in reducers) { |
21 | | - const reducer = reducers[actionName]; |
22 | | - const subs = dispatcher.subscribe(actionName, (payload) => { |
23 | | - state = reducer(state, payload); |
24 | | - }) |
25 | | - subscriptions.push(subs); |
26 | | - } |
27 | | - // Draw UI. |
28 | | - function renderApp() { |
29 | | - const newVdom = view(state, emit); |
30 | | - vdom = patchDOM(vdom, newVdom, parentEl); |
| 7 | + let isMounted = false; |
| 8 | + let vdom = null; |
| 9 | + |
| 10 | + // Reset internal properties of the app. |
| 11 | + function reset() { |
| 12 | + parentEl = null; |
| 13 | + isMounted = false; |
| 14 | + vdom = null; |
31 | 15 | } |
| 16 | + |
32 | 17 | return { |
33 | | - mount(_parentEl) { // Mount to the DOM. |
| 18 | + mount(_parentEl) { |
34 | 19 | if (isMounted) { |
35 | 20 | throw new Error('The application is already mounted'); |
36 | 21 | } |
37 | | - |
38 | 22 | parentEl = _parentEl; |
39 | | - vdom = view(state, emit); |
40 | | - mountDOM(vdom, parentEl); // Only once. |
| 23 | + vdom = hElement(RootComponent, props); |
| 24 | + mountDOM(vdom, parentEl); |
41 | 25 |
|
42 | 26 | isMounted = true; |
43 | 27 | }, |
44 | 28 | unmount() { |
| 29 | + if (!isMounted) { |
| 30 | + throw new Error('The application is not mounted'); |
| 31 | + } |
45 | 32 | destroyDOM(vdom); |
46 | | - vdom = null; |
47 | | - subscriptions.forEach((unsubscribe) => unsubscribe()); |
48 | | - |
49 | | - isMounted = false; |
| 33 | + reset(); |
50 | 34 | } |
51 | 35 | } |
52 | 36 | } |
53 | | - |
54 | | -// createApp({ |
55 | | -// state: { count: 0 }, |
56 | | -// view: (state, dispatch) => `<div>${state.count}</div>`, |
57 | | -// reducers: { |
58 | | -// increment: (state) => ({ count: state.count + 1 }) |
59 | | -// } |
60 | | -// }); |
61 | | - |
0 commit comments