views:

205

answers:

1

as i currently understand, if an event listener is added to an object with useWeakReference set to true, then it is eligible for garbage collection and will be removed if and when the garbage collection does a sweep.

public function myCustomSpriteClass() //constructor
    {
    this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownListener, false, 0, true);
    this.addEventListener(MouseEvent.MOUSE_UP, mouseUpListener, false, 0, true);
    }

in this case, is it not appropriate to initialize an object with weak references event listeners, incase the garbage collector does activate a sweep removing the objects event listeners since they were added during initialization of the object?

in this case, would it only be appropriate to create a type of deallocate() method which removes the event listeners before the object is nullified?

+2  A: 

weak event listeners only means that the listeners are not counted in the garbage collection routine, eg. if an object has no other pointers but strong eventlisteners, it will not be collected by GC, if it only has weak references then it will be removed.

the event listeners themselves are not removed by GC, you have to remove them in the same way if they are weak or strong, however weak referenced listeners should automatically be trashed if the object is nullified.

personally i think that the use of weak listeners promotes bad practices as you no longer have to actually think about what resources you are using, although they are useful in certain situations. I would have a clean-up script to strip it of its listeners that you run before nullification. although there are evangelists for both sides (and he might explain it better if you are still confused)

-edited to make more clear sense-

shortstick
so are you saying event listeners should both use weak references and a clean up function? sorry, your statement confuses me: "if an object has no other pointers but strong eventlisteners, it will not be collected by GC, if it only has weak references then it will be removed. the event listeners themselves are not removed by GC, you have to remove them in the same way." if i'm reading correctly, you said that only weak referenced event listeners will be removed by the GC, but then you say the GC doesn't remove them... ???
TheDarkInI1978
ive edited the post to try and be more explicit. see if it helps comprehension, sorry about the bad wording.
shortstick
ok, i think i'm finally getting it. essentially it's redundant to call removeEventListener on an object that has added the listener with a weak reference, prior to destroying the event listener's target by setting it to null.
TheDarkInI1978
pretty much. keeps you in good practice though :)
shortstick
+1. Weak refs are almost always an excuse for sloppyness.
Juan Pablo Califano