views:

384

answers:

2

When I have an object, removing all references to it is enough to sign it up for the garbage collector, atleast that's what I heard. Eg.:

removeChild(object);
object = null;

I'm still a bit confused though, because does this mean that the event listeners made inside this object's instance are also automatically removed? Or is there anything I need to do?

A: 

an important thing you should consider is that if an object O has eventhandlers, i.e. methods that were added as eventhandlers to E, then this also count as a reference ... unless you add the handler with weakreference ...

also if you have a closure, whose outer scope contains a reference to O, then this is a reference ...

you do not need to remove all references to O, to sign it up for GC either ... the GC also removes circular references ... it removes all "islands" in memory, if you will ... only "peninsulae" connected of the "continent" of builtin objects, i.e. Timers, the display list, I/O layer etc. are not collected ...

the last paragraph of another post of mine deals with this topic a little ...

so yeah, basically, if O gets GCd, then any event handlers get GCd, unless there is another reference to them ... etc.

hope that helped .. :)

back2dos
Note though, that I'm not talking about an event of this object, I'm talking about an event listener _inside_ this object.
Tom
+6  A: 

Ah, you've hit on the crux of memory management in managed code: if you're an object, and you have a reference to another object (even if it's only in the form of an event listener), then you are at least one reason that object won't be removed from memory during a GC.

For display objects, and in my experience pretty much anytime you want to subscribe to an event dispatcher but not be responsible for that dispatcher's remaining in memory, you should add your event listener with the weak reference option:

myPublisher.addEventListener("myEvent", myHandlerFunction, false, 0, true);

In just about every situation I encounter these days, "false, 0, true" (where true means "use weak reference," and which translates loosely as "add this listener, but don't make it a reason for the dispatcher not to get cleared from memory" -- see the docs for more information) is the proper way to add event listeners. Very few textbooks or documentation snippets illustrate this approach for some reason, which is unfortunate, because it makes for a much more intuitive memory-management experience. I'd suggest using it as the rule rather than the exception.

Hope it helps!

Christian Nunciato
+1 - but you should probably state more plainly that Yes, registering for an event listener will keep the object from being GC'ed until it is unregistered, unless you register as a weak listener, in which case it will not.
fenomas