Passing viewables between windows #79
-
I would like to improve my understanding of viewables. I would like to change the parameters of the viewable used by the main window. The only approach I found was to use a global variable. import owlkettle, sequtils
var counter: int = 0
viewable App:
counter: int = 0
viewable ChangeCounter:
selected: int = 0
items: seq[string] = mapIt(0..<100, "Option " & $it)
method view(app: ChangeCounterState): Widget =
result = gui:
Window:
title = "Change Counter"
defaultSize = (200, 60)
Box(orient = OrientY, spacing = 6, margin = 12):
Box(spacing = 6) {.expand: false.}:
Label:
text = "Drop Down"
xAlign = 0
DropDown {.expand: false.}:
items = app.items
selected = app.selected
proc select(item: int) =
app.selected = item
counter = app.selected
Button {.expand: false.}:
text = "OK"
style = [ButtonSuggested]
proc clicked() =
app.closeWindow()
method view(app: AppState): Widget =
result = gui:
Window:
title = "Counter"
defaultSize = (200, 60)
Box(orient=OrientY, spacing=12):
Button {.expand: false.}:
text = "-"
proc clicked() =
app.counter -= 1
Label(text = $app.counter)
Button {.expand: false.}:
text = "+"
style = [ButtonSuggested]
proc clicked() =
app.counter += 1
HeaderBar {.addTitlebar.}:
Button {.addRight.}:
text = "Counter Value"
style = [ButtonSuggested]
proc clicked() =
discard app.open: gui:
ChangeCounter()
app.counter = counter
brew(gui(App())) The main window has a counter which can be updated (extracted from the counter.nim example). Can I avoid the use of the global variable? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You have 2 options:
proc clicked() =
let (res, state) = app.open: gui:
ChangeCounter()
app.counter = ChangeCounterState(state).selected |
Beta Was this translation helpful? Give feedback.
-
Thank you! |
Beta Was this translation helpful? Give feedback.
You have 2 options:
RECOMMENDED If you want to share a lot of state, you probably want to use a proper architecture for your app. I recommend using a Model/View architecture, where you have a
Model = ref object ...
that stores your applications state, and each viewable has amodel: Model
field which it uses as its "data source". Here is an extremely contrived example of this: #39 (comment)If you just want to share a small amount of state between the
ChangeCounter
dialog and theApp
, you can just read it back once the dialog is closed: