Latheesan
Latheesan

Reputation: 24116

Click event on view not firing in Titanium Appcelerator

In my controller, I populate a TableView with rows dynamically by building up an array of TableViewRow and populating it with a View & Image.

Here's the code that creates the View & ImageView and a click event on the view:

// Create product image view
var productImageView = Titanium.UI.createView({
    borderRadius: 5,
    left: 10,
    top: 10,
    bottom: 10,
    width: 130,
    backgroundColor: '#FFFFFF',
    productName: Name,
    imageUrl: ThumbnailUrl,
});
productImageView.add(Titanium.UI.createImageView({
    backgroundColor: '#FFFFFF',
    defaultImage: 'image-missing',
    image: ThumbnailUrl
}));
productImageView.addEventListener('click', function(e) {
    if (e.source.productName && e.source.imageUrl) {
        Alloy.createController('view_product_image', { ProductName: e.source.productName, ImageUrl: e.source.imageUrl }).getView().open({
            modalTransitionStyle: Ti.UI.iPhone.MODAL_TRANSITION_STYLE_COVER_VERTICAL,
            modalStyle: Ti.UI.iPhone.MODAL_PRESENTATION_FORMSHEET
        });
    } else {
        console.log('data not set');
    }
});

When this code runs, within the table row, I can see the image. When I click it, nothing happens. I tried attaching the click event on the ImageView directly also but still nothing happens.

Any ideas why the click event is not getting fired? Should I be subscribing to a different event instead?

Upvotes: 0

Views: 1215

Answers (2)

Suraj kochale
Suraj kochale

Reputation: 973

You are not receiving click event because your event source is imageview and it has no productName and imageUrl property.

To receive click event of view, you need to set touchEnabled property to false of your image view.

productImageView.add(Titanium.UI.createImageView({
    backgroundColor: '#FFFFFF',
    defaultImage: 'image-missing',
    image: ThumbnailUrl,
    touchEnabled :false
}));

however I think instead of adding a listener to each view you can add a common Listener to tableView and handle the event based on e.source.productName property as suggested by others.

Upvotes: 2

Victor Casé
Victor Casé

Reputation: 745

I tried your code and it works for me on iOS and Android. Maybe, can you show the TableView creation?

However, although your solution is correct, it is preferable and more efficient to add a event listener at your TableView not inside a TableViewRow due the number of listeners that will be created, then to reduce the scope of your click event only to the image, You check if the e.source has the productName and imageURL properties (e.g), otherwise you can infer that the click was outside the image.

Try like this:

$.tableView.addEventListener('click', function(e) {
    if (e.source.productName && e.source.imageUrl)
        console.log('hit')
});

Upvotes: 0

Related Questions