HaxeFlixel Tutorial – Button Events, Callbacks

In the Simple Button tutorial, we covered how to create a simple default button (which comes with text). If you check the API, you’ll notice that FlxButton is extended from FlxTypedButton, which does not include text. This means, we can actually use the functions in FlxTypedButton from FlxButton.

One thing that stumped me as a beginner was that the API did not explain how to use the callback events; the onUp, onDown, onOver and onOut variables are exposed, but there was no example on how to use them. I tried these, but it didn’t work:

It turns out, after some Googling, the answer here, in the upgrade guide page, that explains that you have to set the callbacks within those variables:

Note: the OnButtonUp will replace the OnClickButton callback that was set in the new FlxButton(...)  — they use the same onUp event handler.

Okay, we now know how to add callback to the button events. What if you want to trigger the callbacks with arguments? According to the upgrade guide page, you can do this (Let’s reduce the code to just one onDown event for simplicity sake):

It sounds straight-forward, but … let’s say we have 3 buttons, and we want to know which button the player clicked on. How do we code that? There are two ways I could think of.

The first method is just to add and bind simple values for each button’s callback; In the case below, we use the strings “button 1”, “button 2”, and “button 3”.

However, what if, for each button we click, we want to trigger something else within that button? We can pass the button itself as the value:

Pretty cool, huh?

Note: There’s something quirky about the button event behaviour — the onDown event triggers even when you hold your mouse button down and hover over/hover out of the button. This also happens for onUp event. If you want the onDown/onUp to trigger only if the mouse is over the button, you can set allowSwiping to false.

One last thing — what about sound? e.g. Play a sound when the mouse hovers over and out of a button? Check the upgrade guide again, I think the example usage is straight forward. However, just in case you need an example, here is one, based on the code we’ve written above so far (assuming you have the audio file in the /assets/sounds  folder):

I think that about sums up all there is to know about button handling. In the next post, I’ll attempt to cover 9-slice images, and if possible, 9-slice buttons.