jroimartin / gocui

Minimalist Go package aimed at creating Console User Interfaces.
BSD 3-Clause "New" or "Revised" License
9.92k stars 608 forks source link

How to pass extra vars to setkeybinding func? #144

Closed lesovsky closed 6 years ago

lesovsky commented 6 years ago

Hi,

I'd like to pass extra variables into my function which is used in SetKeybinding()

something like this

if err := g.SetKeybinding("viewname", gocui.KeyEnter, gocui.ModNone, myfunction(myvar1, myvar2)); err != nil {
    // handle error
}

Is there any way to do this or I have to use global vars that visible from any funcs?

lesovsky commented 6 years ago

Answer is found.

antonlindgren commented 6 years ago

Hi. Do you mind showing how you solved it? Wondering the same.

lesovsky commented 6 years ago

@antonlindgren Hi, I built shortcuts management in such way:

  1. all shortcuts are defined in an array of structs
  2. iterate over the array and use SetKeybinding() for each shortcut handler
  3. handler's function can accept paramters
    
    type key struct {
    viewname string
    key      interface{}
    handler  func(g *gocui.Gui, v *gocui.View) error
    }

func keybindings(g *gocui.Gui) error { var keys = []key{ {"", gocui.KeyCtrlC, quit}, {"", 'd', funcExample("user_data")}, {"", gocui.KeyEsc, closeHelp}, }

g.InputEsc = true

for _, k := range keys {
    if err := g.SetKeybinding(k.viewname, k.key, gocui.ModNone, k.handler); err != nil {
        return fmt.Errorf("ERROR: failed to setup keybindings: %s", err)
    }
}
return nil

}

func funcExample(c string) func(g gocui.Gui, v gocui.View) error { return func(g gocui.Gui, v gocui.View) error {
switch c { // your application logic here } return nil } }


Hope it helps )))