Skip to content

Instantly share code, notes, and snippets.

@honewatson
Created July 4, 2018 13:33
Show Gist options
  • Save honewatson/d60cf89804607dbeb652841b484441dc to your computer and use it in GitHub Desktop.
Save honewatson/d60cf89804607dbeb652841b484441dc to your computer and use it in GitHub Desktop.
Nim Karax Elm Architecture Example
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()
@moigagoo
Copy link

Hi! How do you split that into components?

@mikebelanger
Copy link

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.

@planetis-m
Copy link

planetis-m commented Dec 8, 2020

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