【问题标题】:How to add event listeners in loop - Titanium Appcelerator如何在循环中添加事件侦听器 - Titanium Appcelerator
【发布时间】:2016-03-01 06:10:46
【问题描述】:

我正在从 POST 查询我的网络服务中获取数据以构建动态菜单。我想要的是系统听到每个视图的点击事件,并识别它是什么。但是我不知道发生了什么,因为没有添加eventListener ...

我的代码如下:

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

【问题讨论】:

  • 我认为更好的是,只需在$.listCategories 上添加一次侦听器,然后在侦听器函数中检查id,如$.listCategories.addEventListener('click', function(e){ alert(e.source.id); });
  • 只是一个实用说明:将听众置于循环中并不是一个好主意。侦听器是被动的,不需要动态分配。我喜欢@Suraj 将它们添加到列表中的想法,然后在需要时调用它们。如果您需要删除它们,您可以遍历列表并迭代地应用removeListener()

标签: dom-events titanium addeventlistener titanium-mobile titanium-alloy


【解决方案1】:

您可以在列表中添加一个 eventListener,而不是在循环中添加 eventListener。

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

你也可以设置

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

只是为了确保您在单击图像或标签时会收到容器视图作为 e.source。

【讨论】:

    【解决方案2】:

    尝试在图像和标签中添加“touchEnabled:false”。比它工作正常(Android,Ti SDK 5.1.1)

    【讨论】:

      【解决方案3】:

      实际上对我有用的是在 for 循环之外创建一个这样的函数:

      function handler(_obj)
      {
          _obj.addEventListener('click',function(e){
              alert(_obj.id);
          });
      }
      

      然后在你的 for 循环中添加以下内容:handler(containerAll);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        相关资源
        最近更新 更多