Today we explore a little storage utility from Hoplon, and build some logic of our game.
Our data is simple vector of 14 numbers, and initial value is:
1 2 |
|
Data will be saved in cell “stem cell”
1
|
|
In HTML our board is simple old fashion table, and text macro will help insert data into it:
1 2 |
|
this text will update when we change our state cell.
Lets write some transitions function which change state. First function reset state to initial and second store random values:
1 2 3 4 5 6 |
|
Simple. And we can add two button for using them with special attribere “on-click” which will take function for call when event received:
1 2 |
|
So this things documented in Getting Started Hoplon.io, and lets detailed see how we can change our state for persistent state which synced with HTML5 Local Storage.
Guys created simple function local-storage
from tailrecursion.hoplon.storage-atom
namespace. Lets see how we can use it:
1 2 3 |
|
Lets dive into standart library, local-storage
take cell and key for which associate data.
1 2 3 |
|
local-storage
is simple proxy who redirect input to html-storage
and add variable js/localStorage
.
html-storage
will create StorageBackend
in js/localStorage
in some key:
1 2 3 |
|
Object StorageBackend
contains 2 function for getting value and for setting and using function pr-str
and read-string
for serializing data:
1 2 3 4 5 6 7 8 |
|
And now we ready to see function store
:
1 2 3 4 5 6 7 8 |
|
In lines 3-4 code check if value is in our local storage, and if not than we save it with -commit!
function of storage, if data is present then we get it, and update our state with it.
After in limes 7-8 we add watcher to cell, so when data in cell changed than data will be saved to localStorage.
add-watch standart Clojure and ClojureScript function and it work for all standart ClojureScript referenced data. But how it could work with cell? Cell type implement cljs.core/IWatchable
protocol by adding some functions:
1 2 3 4 5 6 7 |
|
And -add-watch
simple add key and watch function to hash object property watches
. And -notify-watches
will execute by reset!
or swap!
.
Last step for today is make easy our table by using loop-tpl
which is take some indexes and create <td>
.
1 2 3 |
|
loop-tpl
is not really easy stuff, ‘cause to understand it work, we shoud understand many concepts of Hoplon. And we will do that in future.
I will hold next article awhile, I need some thing to work for Hoplon.
Final web-application you can try at here. Sourch code.