new component example works

This commit is contained in:
Andreas Rumpf 2017-06-19 21:25:34 +02:00
commit 4801b8d8c1
4 changed files with 100 additions and 64 deletions

View file

@ -2,59 +2,68 @@
import vdom, vstyles, karax, karaxdsl, jdict, jstrutils, kdom
type
Car = ref object of VComponent
Carousel = ref object of VComponent
counter: int
cntdown: int
cntdown, myid: int
timer: TimeOut
list: seq[cstring]
change: bool
onclick: proc (ev: Event; n: VNode)
const ticksUntilChange = 5
proc car*(images: seq[cstring]): Car =
new(result)
result.list = images
result.cntdown = ticksUntilChange
proc docount() =
dec result.cntdown
if result.cntdown == 0:
result.counter = (result.counter + 1) mod result.list.len
result.cntdown = ticksUntilChange
else:
result.timer = setTimeout(docount, 30)
result.change = true
redraw()
result.onclick = proc (ev: Event; n: VNode) =
result.change = false
if result.timer != nil:
clearTimeout(result.timer)
result.timer = setTimeout(docount, 30)
method changed(c: Car): bool = true
var
images: seq[cstring] = @[cstring"a", "b", "c", "d"]
proc carousel*(): VNode =
let c = car(images)
proc render(x: VComponent): VNode =
let self = Carousel(x)
proc docount() =
dec self.cntdown
if self.cntdown == 0:
self.counter = (self.counter + 1) mod self.list.len
self.cntdown = ticksUntilChange
else:
self.timer = setTimeout(docount, 30)
self.change = true
redraw()
proc onclick(ev: Event; n: VNode) =
self.change = false
if self.timer != nil:
clearTimeout(self.timer)
self.timer = setTimeout(docount, 30)
let col =
case c.counter
case self.counter
of 0: cstring"#4d4d4d"
of 1: cstring"#ff00ff"
of 2: cstring"#00ffff"
of 3: cstring"#ffff00"
else: cstring"red"
result = buildHtml(tdiv(nref = c)):
text images[c.counter]
button(onclick = c.onclick):
result = buildHtml(tdiv()):
text self.list[self.counter]
button(onclick = onclick):
text "Next"
tdiv(style = style(StyleAttr.color, col)):
text "This changes its color."
if c.cntdown != ticksUntilChange:
text &c.cntdown
text "This changes its color." & &self.myid
if self.cntdown != ticksUntilChange:
text &self.cntdown
var gid: int
proc carousel(): Carousel =
result = Carousel(kind: VNodeKind.component, key: -1)
result.render = render
result.list = images
result.changed = proc (c: VComponent): bool =
let x = Carousel(c)
result = x.change
result.cntdown = ticksUntilChange
result.myid = gid
inc gid
#result.onAttach = proc (_: VComponent) =
# result.cntdown = ticksUntilChange
# kout cstring"attached!"
proc createDom(): VNode =
result = buildHtml(table):