Action Script: Does setting an object to null, automatically remove all attached event listeners?
Lately I've found myself constantly writing removeEventListeners everywhere, which makes code quite messy. I know it's a best practice and such, but in general it has no sense. Garbage collector should handle such a simple task by itself, shouldn't it? Is it that hard to remove all listeners automatically when object is set to null?
So I just want to be sure i开发者_运维问答f that's the case. Does setting an object to null, automatically remove all attached event listeners?
Any insight on this?
UPDATE: In my case scenario is like this - I create an object and attach bunch of event listeners to it, then after a while I need to re-initialize this object. Of course setting this object to null is much easier then unbinding every listener by hand. And on most part listeners are anonymous functions, which means that it's not possible without code refactoring. When I simply re-initialize a variable with new I do not get duplicate listeners and such, but I'm not sure that it's previous value, along with all the listeners gets garbage-collected. Is it?
No, you are not setting the object to null, but the pointer that refers to it. It will not be picked up by the garbage collection unless it is not needed by any other parts of the program, which includes listeners. You need to remove all the listeners yourself, but that should not stop you from finding a less messy way to do it - like a dedicated clearListeners method, or a helper class, etc.
I believe you need to use weak reference when you assign the listeners and than the "nulling" should be enough .
精彩评论