Add a parameter (or even more then one) to Flex event listener

Hi All,

Well, sometimes you find yourself needing a work around to a default framework or language behavior.

I found myself needing exactly that on an application I’m building. No matter what I did I couldn’t find a “normal” way of doing what I did.

This is actually a pretty efficient way of creating your own event listener.

We will talk about the button and we’ll add an event listener.

By default the code looks like this:

 <?xml version="1.0" encoding="utf-8"?>
 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()">
     <mx:Script>
         <![CDATA[
             import mx.controls.Alert;

             private function initApp():void
             {
                 cmdDoAction.addEventListener(MouseEvent.CLICK, showAlert);
             }
             private function showAlert(e:MouseEvent):void
             {
                 //do something here
                 Alert.show(txtInputText.text);
             }
         ]]>
     </mx:Script>
     <mx:Button x="10" y="55" label="Do Action" id="cmdDoAction"/>
     <mx:TextInput x="10" y="10" id="txtInputText"/>
 </mx:Application>

As you can see, the function listening to the click event can only accept one parameter passed to it. This parameter is the event the function is listening to.

Now, what if I want to do another thing: I want to pass the function another parameter. This parameter can be anything - it can be hard coded or it can come from a runtime result of the code.

In the same way, you can add more then 1 parameter of course.

Let us see our code now:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()">
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private function initApp():void
            {
                cmdDoAction.addEventListener(MouseEvent.CLICK, function (e:MouseEvent):void
                {
                    showAlert(txtInputText.text, e);
                });
            }
            private function showAlert(s:String, e:MouseEvent):void
            {
                //do something here
                Alert.show(s, e.target.toString());
            }
        ]]>
    </mx:Script>
    <mx:Button x="10" y="55" label="Do Action" id="cmdDoAction"/>
    <mx:TextInput x="10" y="10" id="txtInputText"/>
</mx:Application>

Now, didn’t I make you happy?

Good luck and happy coding!

<img src="http://feeds.feedburner.com/~r/KensoDev-en/~4/9qtszem3zJQ" height="1" width="1"/>
Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com