Ti.App.addEventListener - Zombies!
Ahhhh, I got some undead eventlisteners in my app!
I very often open subwindow A which communicates itself with own detail-sub-windows B, C & D via Ti.App.addEventListener('myListener',{
Ti.API.info("it’s me!");
});
. I need to instantiate the event within window A because it manipulates table-stuff there.
Now I want to remove that global event listener once my window A closes, but somehow the line Ti.App.removeEventListener('myListener',{});
does not work. Because when I fire that event again MANY event listener instances reply. So they are still alive!
What’s the best practice for the "killing" of global event listener instances?
5 Answers
-
I wrote about a solution here: http://petesaia.com/2012/10/appcelerator-event-garbage-collection/
var globals = {}; globals.EventGarbageCollection = function ( context ) { var instance = this; this.collection = []; this.context = context; this.context.addEventListener('close', function ( ) { instance.empty(); }); }; globals.EventGarbageCollection.prototype = { collect : function ( evt, method ) { this.collection.push([evt, method]); }, addEvent : function ( evt, method ) { Ti.API.addEventListener(evt, method); this.collect(evt, method); }, empty : function ( ) { for ( var i = 0, len = this.collection.length; i < len; i++ ) { Ti.API.removeEventListener(this.collection[i][0], this.collection[i][1]); } this.collection = []; } };
-
I found the solution here (the starred one):
http://developer.appcelerator.com/question/33551/removeeventlistener-not-working -
Here comes an example for my solution. For me it works under 1.4.1 - you don’t need to assign a variable to the event listener. Just add a close-handler to your window where you assigned the Ti.App.eventListener and remove it there again. It even removes multiple instances/threads(?) of one window:
function doit(e) { //do something here } Ti.App.addEventListener('doit', doit); win.addEventListener('close', function() { Ti.App.removeEventListener('doit',doit); });
-
Hi, same issue here. The solution doesn't work with Ti.App.addEventListener. I am encountering this issue only on sdk 1.4.1. It works fine in 1.4.0 even without assigning the eventlisteners to a variable.
Anyone having same issue resolved?
Thanks,
-
Contexts are broken to a certain extent (as of titanium 3.0.2) in that they block Ti.App events. Here is a reference to my answer to a similar question about how to get "real" multi-threading in titanium mobile here