Coding buttons to call functions

Monkey Forums/Monkey Programming/Coding buttons to call functions

Raz(Posted 2011) [#1]
I would like to make a system where I can say... (I guess it's called a callback, right?)
Local tB:Button = New Button()
tB.X = 10
tB.Y = 10
tB.Width = 100
tB.Height = 20
tB.Function = "SaveData()"

So, this will mean, when the button is activated it will call the function SaveData(). Now, I am pretty sure this is not possible, but I am also pretty sure that some of you will have come up with a system to handle this kind of thing. So I am wondering how do you normally go about buttons?

I have two ideas. Each button is an extension of a standard button class, and the Method OnActivate:Void() contains the button specific code. My concern is that this will be alot of code/work if I have a lot of buttons.

My second idea is each button contains a string describing what the button will do and a global function is called to process this string
Function ProcessButtonAction:Void(action:String)
Local tAction = action.split("#") 
Select tAction[0]
Case "main"
GotoMain()
Case "level"
GotoLevel(tAction[1])
End


So if the action string was set to "level#2", the resulting function call will be GotoLevel(2). My concern with this method is that I will have a lots of functions that do not sit within button code, however the upside is I will be able to use said code by actions other than button clicks.

Any thoughts either way from anyone?

-Chris :)


Supertino(Posted 2011) [#2]
Been a while since I looked my own code but this mock code is how I do it.

I'll be happy to post my real code when I get home later if you like.

' my button type
Type TButton
global eventid ' holds which button was activated
field xpos
field ypos
field width
field height
field label:string

function new(blah)
End

End

' Decalre my button
global button_1:TButton

' make my button
button_1 = TButton.New("button name",xpos,ypos,width,height)

' check for button events
Function Events()

Select Tbutton.Eventid
Case button_1
'do this
Case button_2
'do this
End

End function



Raz(Posted 2011) [#3]
Thanks Supertino, that sounds similar to what I was considering (running a string through a select). Don't worry to much about the real code, I get the gist from what you've written there :)


Hima(Posted 2011) [#4]
This is probably more OOP and more flexible

http://www.monkeycoder.co.nz/Community/posts.php?topic=664#5312

Monkey now support interface, so you might want to use that :)


Raz(Posted 2011) [#5]
Hey that's more like it :) Thank you