Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

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!

— asked September 14th 2011 by Mateo Santos
  • iphone
  • listener
0 Comments

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 September 14th 2011 by Doug Handy
    permalink
    2 Comments
    • Oops, really should have placed bSaveClientAdded = true; just inside the if() block, ahead of the addEventListener instead of inside it.

      — commented September 14th 2011 by Doug Handy
    • so true

      — commented June 18th 2012 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');
    }
    
    — answered April 10th 2013 by Marcus Stong
    permalink
    0 Comments
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.