AS3: Weak Listener References Not Appropriate During Initialization?

不想你离开。 提交于 2019-12-24 08:13:08

问题


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?


回答1:


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-



来源:https://stackoverflow.com/questions/2665721/as3-weak-listener-references-not-appropriate-during-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!