Created
July 4, 2018 13:33
-
-
Save honewatson/d60cf89804607dbeb652841b484441dc to your computer and use it in GitHub Desktop.
Nim Karax Elm Architecture Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
include karax / prelude | |
import strutils | |
type | |
Model = object | |
counter*: int | |
Dispatch = proc(model: Model): void | |
proc init(): Model = | |
result = Model(counter: 0) | |
proc up(model: Model, amount: int): Model = | |
result = model | |
result.counter = model.counter + amount | |
proc down(model: Model, amount: int): Model = | |
result = model | |
result.counter = model.counter - amount | |
proc view(model: Model, dispatch: Dispatch): VNode = | |
result = buildHtml(tdiv): | |
button: | |
text "Up 2" | |
proc onclick() = | |
dispatch(model.up(2)) | |
button: | |
text "Down 1" | |
proc onclick() = | |
dispatch(model.down(1)) | |
tdiv: | |
text "count" | |
tdiv: | |
text $model.counter | |
proc runMain() = | |
var model: Model = init() | |
proc dispatch(m: Model): void = | |
model = m | |
proc renderer(): VNode = | |
result = view(model, dispatch) | |
setRenderer renderer | |
runMain() |
In case of Model = ref object
, change the two "funcs" to:
proc up(m: Model, amount: Natural): Model =
result = Model(counter: m.counter + amount)
proc down(m: Model, amount: Natural): Model =
result = Model(counter: m.counter - amount)
...and it wont work, which means this example isn't working correctly (at least as I understand it), there always one instance of Model
and is passed around.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting. But this only allows the state to be either 2 or -1. I had to change the model to
type Model = ref object counter*: int
To get a persistent state.