PDA

View Full Version : Reusing Listener functions



hobbbz
December 7th, 2007, 06:16 PM
Has anyone had any luck reusing listener functions? IE I have a function displayImage(); that I register for displayBtn's MouseEvent.CLICK but I also want to call that function from some other place in the code.

So far i've been doing it by calling it with a new Event such as:
displayImage(new MouseEvent(MouseEvent.CLICK)); so that it won't complain that it doesn't have the arguments it requires. But I feel this sin't the best solution.

How have you done it?

Krilnon
December 7th, 2007, 08:00 PM
If the function doesn't require the event argument, then you can give it a default value.
function displayImage(e:MouseEvent = null):void { /* ... */ }

Otherwise (if you do need to pass in some parameters), it's probably easiest to have the handler call another function instead of having the handler serve as the function that does whatever task you want to be doable without the event.

hobbbz
December 10th, 2007, 12:45 PM
Another technique I tried for one project was using the ellipsis parameter (...rest) for my listener functions so that I could pass it any number of parameters. Don't know if this is the right way either but it worked.

irrationalistic
December 10th, 2007, 07:02 PM
It might be better if you write a single function named displayImage() and then call it from your mouseListener. This would make things a little more straightforward and wouldn't require any crazy parameter hacks...