Titanium Community Questions & Answer Archive

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

Create event listener for dynamically generated labels

Hello all,
I've got a loop set up that creates table rows w/ 3 different views (w/ labels) in each row. I want a user to click different labels to open different windows and not just listen for one click on the table row.

The code below doesn't work which i'm guessing is b/c its outside of the scope of the dynamically created variables that its attached to. I get a warning if i try to move the event listener inside the loop tho.

projNameLabel.addEventListener('click', function(e){});

The code below is how i'm creating all my labels and views in the same for loop.

var projNameLabel = 'titleLabel'+i;
    projNameLabel = Ti.UI.createLabel({
        text: data[i].title,
        left: 0,
        right: 0,
        textAlign:'left',
        shadowColor:'#000',
        shadowOffset:{x:1,y:1},
        color:'#fff',
        font:{fontSize:16},
        height: 'auto'
    });

Might be going about this all wrong so feel free to straighten me out :)

Thx

— asked April 20th 2010 by Kelly Redd
  • dynamic
  • event
  • iphone
  • listener
  • loops
  • mobile
0 Comments

2 Answers

  • It should work if you put the event listener inside the loop.
    I think you are making something else wrong.

    Anyway, another option would be ( I think ) to use the table click event and use the e.source property to get what label is clicked.

    — answered April 20th 2010 by Dan Tamas
    permalink
    0 Comments
  • Thanks Tamas you got me going in the right direction. e.source.ATTRIBUTE was the way to go.
    Just for FYI's here is my solution:

    // snippet from inside my for loop
    var projNameLabel = 'titleLabel'+i;
        projNameLabel = Ti.UI.createLabel({
            text: data[i].title,
            left: 0,
            right: 0,
            textAlign:'left',
            shadowColor:'#000',
            shadowOffset:{x:1,y:1},
            color:'#fff',
            font:{fontSize:16},
            height: 'auto',
         ******btn: 'editbtn'****** // i added this to my other labels as well
        });
    
    // listen for click
    projTable.addEventListener('click', function(e)
    {
        var btn = e.source.btn;
        if (btn == 'editbtn')
        {
            // do something based on condition - probably use a switch/case statement
        }
    });
    
    — answered April 21st 2010 by Kelly Redd
    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.