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({
            image:'images/favorite-off.png',
            width: 34,
            top:20,
            right:30,
            height:30
        });

        (function(){
            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
0 Comments

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
    permalink
    0 Comments
  • 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
    permalink
    0 Comments
  • Does the event fire when the last image is clicked? Try to pass the var favorite into the function (closure) as following.

    (function(favorite){
    var loop…

    })(favorite)

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