Titanium mobile - addEventListener on a view

2019-06-03 08:53发布

问题:

i'm making a scrollable menu using common JS.

An item of the menu is a view that contains 2 others components : a imageView for the icon, and a label for the text of this menu.

The comportement is strange and not the same on the android and ios simulator.

On the android, if a click is done on the label or on the imageview, that gives an : "uncaught TypeError: Cannot Read property..." On iphone, that just don't launch anything.

If i click somewhere else (still into the view item) but not on image or on the labal, for example on an edge, that works just perfect!!

here is the code:

function menuIcons(itemTab) {

var menuMain = Ti.UI.createView({
    layout : 'vertical',
    backgroundColor : '#333333',
    height : 125,
    bottom : 10,
    left : 10,
    right : 10,
    borderRadius : 5.0
});

var menuFirstLine = Ti.UI.createScrollView({
    scrollType : 'horizontal',
    contentHeight : 120,
    contentWidth : 'auto',
    layout : 'horizontal',
    height : 120,
    marginLeft : 5
});

var items = [];
var menuIconsItem = require('view/module/menuIconsItem');

for(var i in itemTab) {
    var page = itemTab[i].page;

    items[i] = new menuIconsItem(itemTab[i]);

    (function(itemsEvent) {
        itemsEvent.id = itemTab[i].id;
        itemsEvent.addEventListener('click', function(e) {

            Ti.App.fireEvent('main_menu_' + itemsEvent.id, {
                id : e.source.id
            });
        })
    })(items[i]);

    menuFirstLine.add(items[i]);
}
menuMain.add(menuFirstLine);
return menuMain;

}

module.exports = menuIcons;

and the code of the items that is required (var menuIconsItem = require('view/module/menuIconsItem');) :

function menuIconsItem(item) {

// path for images on Android  besoin de centraliser tout ca
var pathImages = '';

var itemImage = Ti.UI.createImageView({
    image : item.imageLink,
    width : 64,
    height : 64,
    top : 15
});

var itemLabel = Ti.UI.createLabel({
    color : '#afafaf',
    text : item.text,
    font : {
        textAlign : 'center'
    },
    height : 40,
    top : 80
});

var menuItem = Ti.UI.createView({
    width : 120,
    height : 120,
    backgroundColor : '#424242',
    top : 5,
    left : 5
});

menuItem.add(itemImage);
menuItem.add(itemLabel);

return menuItem;

}

module.exports = menuIconsItem;

回答1:

You have to set the id for the label and image view as well.