How to check if a listener exists ?
Hi, I have a local webview and im using addEventListener to add a new listener.
I have this:
Ti.App.addEventListener('saveClient', function(e){
// My code...
});
This is inserted into a js function. How can I check if a event Listener exists before add it ?
Something like:
if(!checkeventlistener('saveClient')){
Ti.App.addEventListener('saveClient', function(e){
// My code...
});
}
Thanks!
2 Answers
-
Accepted Answer
AFAIK, you can't. Consider also that objects may have multiple event listeners attached, so what you'd really need is a way to enumerate the listener(s) for a given object (or Ti.App in this case).
I'd suggest you keep a global boolean in app.js similar to this:
// in app.js: var bSaveClientAdded = false; // elsewhere: if(!bSaveClientAdded){ Ti.App.addEventListener('saveClient', function(e){ bSaveClientAdded = true; // My code... }); }
If you have numerous listeners, you could use an array to track them and create a function like your checkeventlistener to return whether or not it is in the array, and an addeventlistener you used to track the array.
-
I know this post is a bit old, but thought I would share my solution. I find it's easiest to assign Ti.App event listeners as global object properties.
Declare globals var somewhere in app.js
var globals = {};
And then in whatever file you are declaring a listener
globals.myEventListener = Ti.App.addEventListener('myEventListener', _myEventListener);
And then from anywhere, you can check if it's set
if (!globals.MyEventListener) { alert('do some stuff'); }