I'm trying to figure out the best option to use anonymous event listeners that are 100% garbage collected after use. I got these two examples but I'm wondering if it actually makes any difference between them ...
var listener1:Function = function(e:Event):void
{
resource.removeEventListener(e.type, listener1);
loadedHandler(resource);
listener1 = null;
};
resource.addEventListener(ResourceEvent.LOADED, listener1);
or this one ...
resource.addEventListener(ResourceEvent.LOADED, function(e:Event):void
{
Resource(e.currentTarget).removeEventListener( e.type, arguments["callee"]);
loadedHandler(resource);
}, false, 0, true);
Or would there be any other, better solution? It's very important for me that these listeners and functions get removed correctly from memory because they might be executed very often in the application. I could go and use a Dictionary to map all listeners etc. and test and remove them later in non-anonymous listeners etc. etc. but that would get very involved quickly because there might be situations where resources can be loaded asynchronously at the same time at different classes in the app.
@dominic: You mean placing the function like that into the method body, right? As I wrote above the app loads resources asynchronous and it could happen that a resource is currently being loaded while another class from somewhere else in the app requests the same resource. The resource managing class (in which the said code is) then hooks up to the event listeners dispatched by a resource. As far as I understand this if I use class methods or functions like in your example as listeners they will be re-used by a new request and the events for the older request will never fire. Hence the anonymous functions stored in a variable. I assume they all stay in memory until their respective request is done. But maybe I totally confuse this and it's not the case? I sometimes find the event stuff very hard to grasp.