Reputation: 6292
Hope this makes sense, I am using Titanium mobile to build an iPhone app. I have an array of 100 items each item has an DishID and an DishTitle, I show the DishTitle in a tableview and on the event listener I need to pass the DishID and use alert it for now on the event listener I will later do something with the items ID this is my code so far:
var dishes = eval(this.responseText);
for (var i = 0; i < dishes.length; i++)
{
DishID[i] = dishes[i].DishID;
var row = Ti.UI.createTableViewRow();
row.selectedBackgroundColor = '#fff';
row.height = 30;
row.className = 'datarow';
row.clickName = 'row';
// Create the label to hold the screen name
name[i] = Titanium.UI.createLabel({
color:'#000',
font:{fontSize:16,fontWeight:'bold', fontFamily:'Arial'},
left:5,
top:2,
height:30,
width:200,
text:dishes[i].DishTitle
});
name[i].addEventListener('click', function(e){
alert(DishID[i]);
});
}
The issue I am having I keep getting the same ID 208 no matter which Label I click, am I doing something wrong ?
Upvotes: 0
Views: 867
Reputation: 1130
You've got a scope / closure issue. By the time the 'click' happens, i=208. I find it best to put the eventListener on the table, and custom attribue on the row:
var table = Ti.UI.createTableView();
var rows = [];
for(var i = 0; i < dishes.length; i++) {
var row = Ti.UI.createTableViewRow({
selectedBackgroundColor : '#fff',
height : 30,
className : 'datarow'
});
row.dishId = dishes[i].DishID;
// Create the label to hold the screen name
var label = Ti.UI.createLabel({
color : '#000',
font : {
fontSize : 16,
fontWeight : 'bold',
fontFamily : 'Arial'
},
left : 5,
top : 2,
height : 30,
width : 200,
text : dishes[i].DishTitle
});
row.add(label)
rows.push(row);
}
table.setData(rows);
table.addEventListener('click', function(e) {
alert(e.row.dishId);
});
Upvotes: 1