simonkrauter / NiGui

Cross-platform desktop GUI toolkit written in Nim
MIT License
724 stars 49 forks source link

onClick closure; when created in loop, only last item is bound. #12

Closed enthus1ast closed 7 years ago

enthus1ast commented 7 years ago
import nigui

app.init()

var window = newWindow()
window.width = 250
window.height = 300

var mainContainer = newLayoutContainer(Layout_Vertical)
var ll = ["foo", "baa", "baz"]
for but in ll:
  var control = newButton(but)
  control.widthMode = WidthMode_Expand
  control.onClick = proc(event: ClickEvent) =
    echo but
  mainContainer.add(control)

window.add(mainContainer)

window.show()
app.run() 

https://nim-lang.org/docs/system.html#closureScope was mentioned in the irc so i tried various combinations:

  var control = newButton(but)
  control.widthMode = WidthMode_Expand
  closureScope:
    control.onClick = proc(event: ClickEvent) =
      echo but
  mainContainer.add(control)
  control.onClick = proc(event: ClickEvent) =
    closureScope:
      let foo = but
      echo foo
  mainContainer.add(control)

etc. always the last sequence item is echoed.

Please be aware that the goal is not to get the button description (it only happens to be the same as the but in this example.)

enthus1ast commented 7 years ago

Solution is this:

import nigui

app.init()

var window = newWindow()
window.width = 250
window.height = 300

var mainContainer = newLayoutContainer(Layout_Vertical)
var ll = ["foo", "baa", "baz"]
for but in ll:
  var control = newButton(but)
  control.widthMode = WidthMode_Expand
  closureScope:
      var foo = but
      control.onClick = proc(event: ClickEvent) =
        echo foo
  mainContainer.add(control)

window.add(mainContainer)

window.show()
app.run()