Skip to content
Aug 7 2009 / alecmce

Weak Event Listeners and Inline Methods

I encountered this strange issue today. The useful bulk loader library produces error events when it comes across problems and captures them with the following event listener. The accompanying comment says that this is to prevent unhandled errors that would otherwise produce a stack trace to (debug player) users indicating an error:

addEventListener(BulkLoader.ERROR, function (e:Event):void{}, false, 1, true);

I passed malformed XML into the loader, and found that about 25% of the time, I was getting just such a stack trace. I was not changing anything, but simply running and re-running a whole list of tests, with this test among them. The only thing that I could think of is that the Garbage Collector was occassionally considering the event listener available for collection and was removing it. Testing that hypothesis, I replaced the code with:

addEventListener(BulkLoader.ERROR, squashError, false, 1, true);
...
private function squashError(event:Event):void {}

and the error disappeared. I have posted a patch to the Bulk Library codebase, so hopefully it will be resolved soon.

There’s Nothing New Under The Sun

I’ve known about Grant Skinner’s analysis of event listeners for years, and have accepted that event listeners should always be defined weakly for as long. However, that article contains the very point that I have spent an afternoon rediscovering! It turns out I’ve been doing work that Grant Skinner did three years ago on behalf of another third party library vendor… which is disheartening because if I knew that article in more detail I could have saved my afternoon. It’s encouraging as well though; there’s a cliché about earning your learning somewhere…