Titanium Community Questions & Answer Archive

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

EventListener not attaching in a loop

I am pulling my hair out with (what I am sure is a simple) problem.

I have the following code:

        var favorite = Titanium.UI.createImageView({
            width: 34,

            var loopFavorite = favorite;
            favorite.addEventListener('click', function(e) {
                loopFavorite.image = (loopFavorite.image == 'images/favorite-on.png') ? 'images/favorite-off.png' : 'images/favorite-on.png';



The issue is that the click event never fires. No matter what code I put in the listener. (e.g. Ti.API.info('test');).

This is in a for loop so I have put it in a closer, but still nada. The crazy thing is that in the same for loop I have a listener that is firing just fine.

I am adding the favorite to the table row later in code, in case you think that is the issue. The image shows up as expected, just the event listener does not seem to attach itself.

Any Ideas?

— asked June 22nd 2010 by Phillip Williams
  • addeventlistener
  • closer
  • loop

3 Answers

  • It turns out there is some off behavior with the ImageView. At the suggestion of Kevin, I switched it to a standard view and used the backgroundImage property. Everything worked as expected.

    — answered June 24th 2010 by Phillip Williams
  • try to create a favorites array outside of the loop. use code like this to attach an event

    favorite[i].addEventListener('click', function(e) {


    i hope this explanation is of any help to you!

    — answered June 22nd 2010 by Christian Sigl
  • Does the event fire when the last image is clicked? Try to pass the var favorite into the function (closure) as following.

    var loop…


    — answered June 23rd 2010 by Xiyuan Shen
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.