AS3:初始化期间弱侦听器引用不合适?

发布于 2024-08-29 12:33:54 字数 484 浏览 3 评论 0原文

据我目前的了解,如果将事件侦听器添加到 useWeakReference 设置为 true 的对象中,那么它就有资格进行垃圾收集,并且在垃圾收集进行扫描时将被删除。

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

在这种情况下,如果垃圾收集器确实激活了清除对象事件侦听器的清除操作,因为它们是在对象初始化期间添加的,那么用弱引用事件侦听器初始化对象是否不合适?

在这种情况下,是否只需要创建一种 deallocate() 方法来在对象无效之前删除事件侦听器?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溺孤伤于心 2024-09-05 12:33:54

弱事件侦听器仅意味着侦听器不计入垃圾收集例程,例如。如果一个对象除了强事件监听器之外没有其他指针,那么它不会被GC收集,如果它只有弱引用那么它将被删除。

事件侦听器本身不会被 GC 删除,无论它们是弱还是强,您都必须以相同的方式删除它们,但是如果对象无效,则弱引用侦听器应该自动被丢弃。

我个人认为,使用弱侦听器会导致不良做法,因为您不再需要实际考虑您正在使用哪些资源,尽管它们在某些情况下很有用。我将有一个清理脚本来删除您在无效之前运行的侦听器。 尽管双方都有传道者(他可能会解释如果您仍然感到困惑,那就更好了)

-经过编辑以使其更清晰-

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-

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文