Some Pixels en / pt

Passing parameters to Event handlers

One year ago I asked Beck Novaes how to pass parameters to Event Handlers added dynamically, because when you add a Event Listener using myComp.addEventListener(...), the handler must wait only one event parameter. So Beck came up with a solution, but he stated that this is just one "alternative" solution, not the better one.

Some days ago I was working with simultaneous requests to the server and I wanted to keep the data I sent on the request but I didn't want to return it from Java, so I came up another solution. Assuming that your Event Handler is waiting a Function that have only one Event parameter, I created another Function that returns a Function waiting the Event parameter. But the trick is that the Function Closure scope allows you to access parameters passed to the first and the second Function, so you can do this:

<mx:Application xmlns:mx="" height="100%" width="100%"

            private function initApp():void
                buttonA.addEventListener(MouseEvent.CLICK, buttonHandler(0x0000FF));
                buttonB.addEventListener(MouseEvent.CLICK, buttonHandler(0xFF0000));

            private function buttonHandler(color:uint):Function
                return function(event:MouseEvent):void
                    box.setStyle("backgroundColor", color);

        <mx:Button id="buttonA" label="Blue"/>
        <mx:Button id="buttonB" label="Red"/>

    <mx:Box id="box" height="80" width="200" backgroundColor="#FFFFFF"/>


And now, what if you want to use this Event Handler directly in MXML? Well, you can't do this:

<mx:Button label="Green" click="buttonHandler(0x00FF00)"/>

This will not work because the Function that returns from the first one is waiting the Event parameter. So you can do this:

<mx:Button label="Green" click="buttonHandler(0x00FF00)(event)"/>

Weird, huh? Maybe another FreaktionScript pattern?