I understand how weak references work, but I am bit confused regarding it's use in actionscript event listeners. Consider the example below:
public class Rectangle extends MovieClip {
public function Rectangle() {
var screen:Shape=new Shape();
screen.addEventListener(MouseEvent.MOUSE_OUT, new Foo().listen, false, 0, true);
addChild(screen);
}
}
public class Foo extends MovieClip {
public function listen(e:MouseEvent):void {
trace("tracing");
}
}
Now here, since there is only a weak reference to Foo, would not the event listener Foo be garbage collected if and when the garbage collector runs and the code stop working as expected?
Is the weak event listener scenario prescribed only for event listener methods within the same class as below?
public class Rectangle extends MovieClip {
public function Rectangle() {
var screen:Shape=new Shape();
screen..addEventListener(MouseEvent.MOUSE_OUT, listen, false, 0, true);
addChild(screen);
}
public function listen(e:MouseEvent):void {
trace("tracing");
}
}
In the above scenario, is this how weak event listeners help?
If the Rectangle object has no other references, then it is a candidate for garbage collection, but since there is an event listener within the object, the event dispatcher holds a reference to the object, even though there are no other references to the object(other than the one held by the event listener). Hence it is prevented from being garbage collected. Is this the reason why weak event listeners are prescribed? Is the flash player so naive that, it cannot figure out that the event listener is defined within the same object?