How to check if a listener exists ?

You must Login before you can answer or comment on any questions.

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.

— answered 2 years ago by Doug Handy
answer permalink
2 Comments
  • Oops, really should have placed bSaveClientAdded = true; just inside the if() block, ahead of the addEventListener instead of inside it.

    — commented 2 years ago by Doug Handy

  • so true

    — commented 12 months ago by Abhishek Shah

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');
}

Your Answer

Think you can help? Login to answer this question!