Flex Alert! Listen to the buttons
The question of how to handle/listen to button clicks from the Alert control pops up (excuse the pun) quite often. To do this you need to create an actionscript function to handle the event. Other situations may arise where you also need to pass further information to the handler function. This post will show you how ![]()
The mx.controls.Alert class has a static method that shows the Alert control with the title, message, and requested buttons. The following code block will demonstrate how to declare a listener for your Alert control, as well as what to do when you catch the event.
In short, the code shows how to create an Alert control which has 2 buttons, Yes and No. Keep an eye out for for line 12 – this is where we delegate the button click listener to the handleAlert method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import mx.controls.Alert; import mx.utils.Delegate; // show the Alert control public function showAlert() : Void { // the show method follows the method signature from the Flex Actionscript API Alert.show( "Are you sure?", "Confirm Delete", Alert.YES| Alert.NO, null, Delegate.create(this, this.handleAlert), null, Alert.YES); } // handle the Alert control button click public function handleAlert( event:Object ) : Void { if( event.detail == Alert.YES) { // YES button was clicked } else if( event.detail == Alert.NO) { // NO button was clicked } } |
Quite similarly we can also create an inline function, which will allow us to pass extra variables to the handler method. Take a look at the following and how it declares a function which takes an event object and then makes a call to our own handleAlert method:
3 4 5 6 7 8 9 10 | //line 12 replacement Delegate.create( this, function(event){this.handleAlert(event, "hello");} ) //modified alertHandler method signature public function handleAlert( event:Object, test:String ) : Void { //handle the event.detail property etc } |
You can see that the above example passes the string hello through to our handleAlert method. Don’t forget to change the method signature for the handleAlert method to compensate for the extra variable(s).
Now you can not only create, but successfully listen to and handle the button clicks from within an Alert control. Keep an eye out for another post soon where I’ll demonstrate how to further customise the Alert control, but also outline the setbacks with its current implementation

