Reputation: 3078
Let's say there's a class which loads a bunch of images and dispatches an Event.COMPLETE when finished. We'll call it AssetLoader
Then we have our main document class which does something like this:
var myAssetLoader:AssetLoader = new AssetLoader();
myAssetLoader.addEventListener(Event.COMPLETE, function():void {
doStuffWithImages();
});
myAssetLoader.loadURLS("http://example.com/image1.png", "http://example.com/image2.png");
//Some time later, after doStuffWithImages()
myAssetLoader = null
Will myAssetLoader be completely garbage collected? i.e. without any removeEventListener?
Upvotes: 0
Views: 98
Reputation: 18193
In this case, yes, your AssetLoader would be garbage collected. Whether the event handler is an anonymous function or not.
The key is paying attention to which object maintains the reference to the other object when adding an event listener: When you say a.addEventListener("event", b.eventHandlerFunction), the "a" object maintains a reference to the "b" object (when the event happens "a" needs to execute the event handler in "b").
So if we discard "a", and keep "b" in memory, "a" can be garbage collected because no object has a reference to it. In your case "b" is the main document class, which the anonymous function belongs to... and "a" is the AssetManager.
That being said the advice given in the other answer are still good practices to follow, even if you know your objects will get g/c'd.
Upvotes: 1
Reputation: 2161
You should removeEventListener
before setting the references to null.
Upvotes: 1