最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does each addEventListener require a removeEventListener to prevent memory leak in Appcelerator - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Jan 31, 2017 at 0:16 foreverdumbforeverdumb 511 silver badge2 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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). All the UI elements in local scope within a window will be removed from memory the moment that window is closed. 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. I usually not remend 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论