简体   繁体   中英

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?

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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