Are there any problems using nested functions with eventlisteners?
I just opened nested functions in AS3 (yes late to the party) and I am using them in a Flex project. I have always disliked using separate functions for essentially modal operations with eventListeners - it adds clutter to the code and separates the logic of work, and also cannot easily reference local variables.
The example below for a user who selects a directory seems to work pretty well and is good, but I'm wondering if there are any issues I'm not familiar with with this approach. Also, with a modeless operation (like asynchronous, like using Loader
), can nested functions be used?
private var rootDirectory:File;
protected function rootBtn_clickHandler(event:MouseEvent):void
{
var tmp:File = File.desktopDirectory;
tmp.browseForDirectory("Set Project Folder");
tmp.addEventListener(Event.SELECT, onUserSelect);
tmp.addEventListener(Event.CANCEL, onUserCancel);
function onUserSelect(event:Event):void
{
tmp.removeEventListener(Event.SELECT, onUserSelect);
tmp.removeEventListener(Event.CANCEL, onUserCancel);
rootDirectory = event.target as File;
}
function onUserCancel(event:Event):void
{
tmp.removeEventListener(Event.SELECT, onUserSelect);
tmp.removeEventListener(Event.CANCEL, onUserCancel);
trace("user canceled");
}
}
source to share
There may be some caveats when using anonymous or nested functions.
The first and most important is garbage collection:
In your example, the only thing that prevents your object from tmp
being garbage collected is the listeners themselves SELECT
and CANCEL
. Since you are not setting the weak flag to true this should not be a problem, however if you are using the weak flag ( tmp.addEventListener(Event.SELECT, onUserSelect,false,0,true)
) then there is a decent change, the object tmp
will get garbage collected before the user CHOOSING or UNDOING the file.
Also, you need to remove every listener you hooked up this way. You are doing this in your method onUserCancel
, so it should be fine, but if you haven't, then you will have a memory leak on your hands, as every time your click handler runs another instance will be created tmp
but never get garbage collection because of the listeners attached to it.
As such, most people stay away from anonymous / nested methods in AS3 (and I usually / usually recommend it to people) because it's easy to create memory leaks or get garbage collected by accident. There may or may not be performance differences, but I've never run benchmarks in this regard.
source to share