State management
Currently, in the Javascript ecosystem there are incredible state management libraries and for complex applications we recommend that you use one with Bemtv, however Bemtv also offers a simple way to manage the state, called “state functions”.
Bemtv believes that the Javascript modules already offer enough resources to manage the state, so stateFn()
was created to take advantage of the javascript modules.
Basically, it is a function which can optionally function as both a getter and a setter and has a watch()
method to allow you to watch the state.
but if we need more control we can force our “stateFn” to work only as a getter and only allow the state to be changed through “actions”:
Note in the examples above that we pass a second argument true
which tells stateFn()
to return a function that works just like a getter.
Now the return of the stateFn()
function is a tuple where the first item is a function that just gets the current value of the state and the second is a function to set the state.
Now let's use the javascript modules to provide isolation and create our “actions”:
Note in the examples above the toggleTheme()
function that changes the current theme, it is an “action” because taking advantage of having access to the setTheme()
function with that it can change the state.
Another important thing is that we only export the “actions” and the $theme()
function, which works like a normal function when called, just returning the current value without allowing the state to be changed.
stateFn().watch()
To react to state changes we can use the watch()
method which accepts a callback/listener and fires it immediately and on each state change:
The listener also takes a second argument which is the number of times the listener has already been called:
To remove the listener just call the function returns by the watch()
method:
Last updated