Create event listener for dynamically generated labels

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

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

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.

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

Your Answer

Think you can help? Login to answer this question!