javascriptdom-eventstitaniumtitanium-mobile

Add event to dynamically generated sliders on Titanium SDK


I'm facing this problem, I'm generating dynamically sliders from an array of items (strings), I use an object to create dynamically the variable and then add an event listener to the variable I'm just creating but it won't work.

The variable itemsObject[labelValue] it is not changing its text value when the change event is detected.

var items = ['Love',
        'Angry',
        'Jealous',
        'Happiness',
        'Understanding'];
                    
                    
//all the controls on this view                 
var itemsObject = {};


var scrollView = Titanium.UI.createScrollView({
    contentWidth:'auto', 
    contentHeight:'auto', 
    top:0, 
    showVerticalScrollIndicator:true, 
    showHorizontalScrollIndicator:false,
    touchEnabled: true 
}); 

var viewInsideScrollView = Ti.UI.createView({ 
    width:'310dp', 
    height:'auto', 
    top:0,
    touchEnabled:false 
}); 

scrollView.add(viewInsideScrollView);


var fromTopItem  =30,
    fromTopSlider=50,
    fromTopLabelValue =25;

for(i in items){
    
    var label = items[i] + 'Label';
    //item name
    itemsObject[label] = new Ti.UI.createLabel({
        text: items[i],
        color: '#ffffff',
        top:fromTopItem,
        height:'auto',
        width:'auto'
    });

    fromTopItem+=70;
    
    var slider = items[i] + 'Slider';

    //slider control
    itemsObject[slider] = Titanium.UI.createSlider({
        top:fromTopSlider,
        min: 0,
        max: 5,
        minRange: 0,
        maxRange:5,
        width: '95%',
        value: parseInt(Math.random() * (5 - 0) + 0) //values from 0 to 5
    });
    
    fromTopSlider+=70;
    
    var labelValue = items[i] + 'LabelValue';
    
   //value selected
   itemsObject[labelValue] =  new Ti.UI.createLabel({
        text: itemsObject[slider].value,
        color: '#ffffff',
        top:fromTopLabelValue,
        left:285,
        height:'auto',
        width:'auto',
        font:{
            fontSize:24,
            fontWeight: 'bold'
        }
    });
    
    fromTopLabelValue+= 70;
    
    //listener
    itemsObject[slider].addEventListener('change', function(e){
        itemsObject[labelValue].text = parseInt(e.value);
    });
    
//adding to the view
    viewInsideScrollView.add(itemsObject[label]); 
    viewInsideScrollView.add(itemsObject[labelValue] );
    viewInsideScrollView.add(itemsObject[slider] );
    
}



self.add(scrollView);

Solution

  • I solved it, it was a problem of scope so I put the controls creation within a function and then call that function with a loop.