简体   繁体   English

每个addEventListener是否都需要removeEventListener来防止Appcelerator中的内存泄漏

[英]Does each addEventListener require a removeEventListener to prevent memory leak in Appcelerator

If I have a simple alert dialog such as 如果我有一个简单的警报对话框,例如

                  var dialog = Ti.UI.createAlertDialog({
                    cancel: 1,
                    buttonNames: ['OK'],
                    message: 'Here is message.',
                    title: 'Title'
                  });
                  dialog.addEventListener('click', function(e){
                    // do something
                  });
                  dialog.show();
                  dialog = null;

within a window. 在一个窗口内。 Let's say I close that window and that window instance is not assigned any variable. 假设我关闭了该窗口,并且该窗口实例未分配任何变量。 The window should be garbage collected. 该窗口应该被垃圾收集。 Will 'dialog' eventually be freed during garbage collection or because I never call dialog.removeEventListener it will forever live in memory? 最终将在垃圾回收期间释放“对话”,还是因为我从不调用dialog.removeEventListener,它将永远存在于内存中?

In your example you do not need to remove the event listener. 在您的例子中,你不需要删除事件侦听器。

To prevent memory leaks the only thing that you need to do in this case is to make sure you declare var dialog instead of just dialog (which you did well). 为了防止内存泄漏,在这种情况下,您唯一需要做的就是确保声明var dialog而不是仅仅dialog (您做得很好)。 All the UI elements in local scope within a window will be removed from memory the moment that window is closed. 窗口关闭后,窗口中本地范围内的所有UI元素都将从内存中删除。 If you declare global references it may cause memory issues. 如果声明全局引用,则可能会导致内存问题。

Now there are cases where you MUST remove event listener and those are the custom event listeners. 现在,在某些情况下,您必须删除事件侦听器,而这些是自定义事件侦听器。 Adding custom events specially to the Ti.App object and not removing them will cause you a lot of trouble. 专门向Ti.App对象添加自定义事件而不删除它们会给您带来很多麻烦。 I usually not recommend to add any but in case you really really need it you should make sure that's removed, also make sure that the event handler is a named function. 我通常不建议添加任何内容,但如果确实需要,请确保将其删除,并确保事件处理程序是命名函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM