Created
July 20, 2018 09:58
-
-
Save stedi67/c242576b169ffd0d031a3858efe51dba to your computer and use it in GitHub Desktop.
karax using elm architecture
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
import patty | |
import strformat | |
import strutils | |
import sugar | |
include karax / prelude | |
include karax / kdom | |
include karax / kajax | |
type | |
Model = object | |
counter*: int | |
number*: cstring | |
numberwisdom*: cstring | |
variant Message: | |
Increment | |
Decrement | |
SetNumber(next: proc(msg: Message): void) | |
Save(resultstring: cstring) | |
type | |
Dispatch = proc(msg: Message): void | |
proc runAjaxResult(dispatch: Dispatch) : auto = | |
(httpStatus: int, response: cstring) => | |
dispatch(Save(resultstring=response)) | |
proc update(msg: Message, m:Model) : Model = | |
result = m | |
match msg: | |
Increment: result.counter = m.counter + 1 | |
Decrement: result.counter = m.counter - 1 | |
SetNumber(next: cont): | |
let x = getVNOdeById("numberInput") | |
result.number = x.text | |
let ajaxFunc = runAjaxResult(cont) | |
ajaxGet(fmt"http://numbersapi.com/{result.number}", @[], ajaxFunc) | |
Save(resultstring: res): result.numberwisdom = res | |
proc view(model: Model, dispatch: Dispatch): VNode = | |
result = buildHtml(tdiv): | |
button: | |
text "Up" | |
proc onclick() = | |
dispatch(Increment()) | |
button: | |
text "Down" | |
proc onclick() = | |
dispatch(Decrement()) | |
tdiv: | |
h2: | |
text "count" | |
tdiv: | |
text $model.counter | |
h2: | |
text "number wisdom" | |
input(id = "numberInput", type="number", min="2"): | |
proc onchange() = | |
dispatch(SetNumber(next=dispatch)) | |
tdiv: | |
text $model.numberwisdom | |
proc model_init(): Model = | |
result = Model(counter: 0, numberwisdom: "empty", number: "0") | |
proc runMain() = | |
var model: Model = model_init() | |
proc dispatch(msg: Message): void = | |
model = update(msg, model) | |
proc renderer(): VNode = | |
result = view(model, dispatch) | |
setRenderer renderer | |
runMain() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment