Skip to content

Instantly share code, notes, and snippets.

@mauropm
Created March 22, 2013 22:39
Show Gist options
  • Save mauropm/5225308 to your computer and use it in GitHub Desktop.
Save mauropm/5225308 to your computer and use it in GitHub Desktop.
Example about how to handle window closing in Android, doing: Cleaning of the window's contents, remove all listeners and proper closing and null of the window.
Ti.include('utils.js');
// Base window
var win = Ti.UI.createWindow();
// Base launch button
var button = Ti.UI.createButton({
title:'Press here',
top: 10,
left: 10,
});
// Function to clean the win2 (i.e., remove all the attached listeners, close it, null it)
function win2Clean(){
if(win2!=null){
win2.close();
clean(win2);
unRegisterAllEventListeners(win2);
win2 = null;
}
Ti.App.removeEventListener('win2:close',win2Clean);
}
var win2 = Ti.UI.createWindow({
backgroundColor:'white',
});
function win2Close(){
Ti.App.fireEvent('win2:close');
}
button.addEventListener('click',function(){
win2 = win2 || Ti.UI.createWindow({
backgroundColor:'white',
});
registerEventListener(win2, {event: 'android:back', callback: win2Close});
Ti.App.addEventListener('win2:close',win2Clean);
win2.open();
});
win.add(button);
win.open();
/// Recursive Clean of Memory
// by Mauro Parra
// https://gist.github.com/mauropm/2655813
// Begin recursive clean of memory
function do_clean(e,c){
clean(c);
e.remove(c);
Ti.API.info( 'Deleted child at do_clean' );
return;
}
function clean(e){
if (e!=null){
if(e.children){
Ti.API.info( 'Number of children: ' + e.children.length );
for(var i = 0; i<e.children.length;i++){
do_clean(e, e.children[0]);
}
} else {
return;
}
}
}
// End recursive clean of memory
/// <<< Register & UnRegister Event Listeners
// Original from: https://gist.github.com/minhnc/2333095
// Thanks minhnc!
/**
* params: {event: 'event', callback: eventCallback}
*/
function registerEventListener(obj, params) {
if ( typeof obj._eventListeners == 'undefined' ) {
obj._eventListeners = [];
}
obj.addEventListener(params.event, params.callback);
var eventListeners = obj._eventListeners;
eventListeners.push(params);
obj._eventListeners = eventListeners;
Ti.API.info( JSON.stringify(obj._eventListeners) );
}
function unRegisterAllEventListeners(obj) {
if ( typeof obj._eventListeners == 'undefined' || obj._eventListeners.length == 0 ) {
return;
}
for(var i = 0, len = obj._eventListeners.length; i < len; i++) {
var e = obj._eventListeners[i];
obj.removeEventListener(e.event, e.callback);
}
obj._eventListeners = [];
}
/// Register & UnRegister Event Listeners >>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment