dom-eventstitaniumaddeventlistenertitanium-mobiletitanium-alloy

How to add event listeners in loop - Titanium Appcelerator


I am bringing data from a POST query my webservice to build a dynamic menu. What I want is that the system hear the click event of each view, and identify what it is. But I do not know what's going on because the eventListener is not added ...

My code below:

getCategorias.onload = function() {
            
    var json = this.responseText;
    var response = JSON.parse(json);
    
    
    for(var i = 0; i < response.length; i++) {
        var containerAll = Ti.UI.createView({
            width: "100%",
            height: 130,
            backgroundColor: "#000",
            id: response[i].id
        });
    
        
        
        var viewImage = Ti.UI.createView({
            backgroundImage: "http://www.iconomize.com.br/admin/"+response[i].foto, 
            backgroundColor: "#000",
            opacity: "0.5",
            width: "100%", 
            height: "100%",  
            top: "0"
        });
        
        var labelCat = Ti.UI.createLabel({
            color: "#fff",
            textAlign: "center",
            width: "90%",
            text: response[i].nome
        });
        
        
        containerAll.addEventListener('click', function(e){
            alert(e.source.id);
        });

        
        containerAll.add(viewImage);
        containerAll.add(labelCat);
        

        $.listCategories.add(containerAll);
        
    }
    
    
    $.activityIndicator.hide();
};

Solution

  • Instead of adding eventListener in loop, you can add a eventListener on list.

    $.listCategories.addEventListener('click', function(e){ 
       alert(e.source.id);
       //Do the required thing by using container id
    });
    

    Also you can set

    viewImage.touchEnabled = false;
    labelCat.touchEnabled = false;
    

    Just to make sure you will receive container view as e.source when click on image or label.