dev-resources.site
for different kinds of informations.
Create a very simple State Machine with closures
Published at
10/30/2022
Categories
javascript
mvu
Author
artydev
Author
7 person written this
artydev
open
State machine are a great way to render consistent view.
Here is a very simple example of a state machine created via a closure.
Once the state machine created, you simply pass it the desired transition, and the state machine returns the updated one.
You can test it here SimpleStateMachineDemo
const {m, dom, udom, render, html } = MVU;
const h1 = m("h1");
const button = m("button");
function evaluate_state_machine (state, transition) {
switch(transition) {
case("inc") :
state = {...state, counter : state.counter += 1 }
break;
case("dec") :
state = {...state, counter : state.counter -= 1 }
break;
default:
state = state
}
return state;
}
function state_machine () {
let state = {
counter : 0
}
function _state_machine (transition) {
state = evaluate_state_machine(state, transition);
return state;
}
return _state_machine;
}
function App (sm) {
let state = sm();
let app = dom ();
h1(`State machine demo : ${state.counter}`)
button("inc").onclick = () => { sm("inc"); update_app (sm)};
button("dec").onclick = () => { sm("dec"); update_app (sm)};
udom ();
return app;
}
let sm = state_machine();
function update_app (sm) {
render(app, App(sm));
}
update_app (sm);
mvu Article's
13 articles in total
VanJS and a spice of DML, my Holy Graal Quest is finished...
read article
MVU update
read article
A Color Chooser in 64 lines of JS with MVU
read article
A Very Simple Game in plain JS
read article
Create a very simple State Machine with closures
currently reading
Why I use MVU ?
read article
The state of MVU
read article
Morphdom and MVU, don't overlook this !
read article
Readable vs Workable Code
read article
Organizing MVU Projects
read article
Life after Elm: What we did
read article
ClojureScript MVU routing
read article
ClojureScript async MVU
read article
Featured ones: