December 14, 2009

Passing parameters to an EventHandler in ActionScript

I ran into a problem the other day when I wanted to pass parameters to an EventHandler. What I wanted to achieve was to add 2 handlers (MouseEvent.MOUSE_OVER and MouseEvent.MOUSE_OUT) in order to change the background color of some canvases. The parameters I wanted to pass was canvas and color to use.

This is the solution I came up with:
canvas.addEventListener(MouseEvent.MOUSE_OVER, getHandler(canvas, 0x404040));

private function getHandler(canvas:Canvas, color:uint) : Function {
return function(event:MouseEvent) : void {
changeBackgroundColor(canvas, color);
}
}

private function changeBackgroundColor(canvas:Canvas, color:uint) : void {
canvas.setStyle("backgroundColor", color);
}

0 comments: