kleindynamic
v0.0.3
Published
This library also handles state management as dynamic valeus can be stored raw in the state. These can then be serialised to be stored anywhere json can be. In the example, indexedDB is used to retain application state across reloads and tabs.
Downloads
218
Readme
A dynamic wrapper for kleinui
This library also handles state management as dynamic valeus can be stored raw in the state. These can then be serialised to be stored anywhere json can be. In the example, indexedDB is used to retain application state across reloads and tabs.
To use this library it is recommended to have a global state object like so:
var globalState = {
count: 0
}
We could then use this value in our counter application:
export function counter() {
return new container(
new button("-").addEventListener("click", ()=>{globalState.count--}),
new kleinTextNode(globalState.count.toString())
new button("+").addEventListener("click", ()=>{globalState.count++}),
)
}
However, on running this you will notice that the text node will not change as it has not been rerendered. While you could trivially add this, with larger applications where a change to one piece of state may cause multiple ui updates, this can become messy.
Here's where this library comes in, we can wrap the text node in a dynamicNode
class and instead pass a function that returns our UI nodes. The suceeding arguments define which values must change to in order to trigger a rerender.
export function counter() {
return new container(
new button("-").addEventListener("click", ()=>{globalState.count.V--}),
new dynamicNode(()=>
new kleinTextNode(globalState.count.V.toString())
, globalState.count).node,
new button("+").addEventListener("click", ()=>{globalState.count.V++}),
)
}
You will see that I have also added .V
after count and this is because we will also have to chnage our global state to use dependableValue
which stores the actaul value in a property called V
.
var globalState = {
count: new dependableValue(0, "counter")
}
The second argument here is simply a unique id that is neccesary for deserialisation but the name is unimportant.
You can also use dependableValue
with objects, however, changes are only detected if the entire object is replaced as the mechanism to detect chnages is simply a getter and setter on the V property. This could be changed by providing a proxy of the object but I decided that this could add perfomance problems and could cause unneccesary rerenders. A suitable compromise, is therefore to call dependableValue.update()
once you are ready for a rerender of all dependants.