Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of inline closures / function delegates in Actionscript

Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them.

I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name.

Are there any catches of using them? Do they work pretty much the same way as in C#.

I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them!

private function showPanel(index:int):void {    

_timer = new Timer(1000, 1);        
_timer.addEventListener(TimerEvent.TIMER, function(event:Event):void 
{
    //  show the next panel
    showPanel(index++);
});
like image 682
Simon Avatar asked Oct 17 '08 21:10

Simon


1 Answers

The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them.

But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function.

Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example).

Hope this helps.

like image 69
Mitch Haile Avatar answered Nov 06 '22 11:11

Mitch Haile