button on top of a clickable view

You must Login before you can answer or comment on any questions.

I have a button on top of a view. Both have a click event. When i click on the button, the view also receive a click event. That s not normal! how can i prevent that behavior?

var view = Ti.UI.createView();
view.addEventListener('click', function(){Ti.API.info('click1');});
var button = Ti.UI.createButton({width:50, height:50});
button.addEventListener('click', function(){Ti.API.info('click2');});
view.add(button);
if i click on button, i get click2 and click1

2 Answers

Accepted Answer

Try this:

var view = Ti.UI.createView({
    _type: 'view'
});
view.addEventListener('click', function(e) {
    if ( e.source._type != 'view' ) {
        return;
    }
 
    Ti.API.info('click1');
});

That's normal and it is called event bubbling. Currently, Titanium has no means to prevent event bubbling, but you can check if view is the source of the click:

view.addEventListener('click', function(e){
    //this is view inside event listener
    if (this === e.source) {
        //view is the source
    }
});

— answered 1 year ago by Ivan Škugor
answer permalink
8 Comments
  • Actually, you can decide if an object should be 'clickable' or whether it passes it's click event to it's parent. I use this often when embedding objects in tableviewrows. I want the row to receive the click event, not the objects in the row. Set touchEnabled = false; to have an item pass it's click event to it's parent. This way you get only one event to process.

    — commented 1 year ago by Ray Belisle

  • this === e.source: This will prevent event to be fired even when you click on view.

    — commented 1 year ago by Minh Nguyen

  • @Ray - that does not seem prevent event bubbling. Try to prevent row click event using that technique if component inside row is clicked.

    @Minh - That condition won't prevent event firing. That condition just check if the source of the event is the same as the component that has that listener. ;)

    — commented 1 year ago by Ivan Škugor

  • Show 5 more comments

Your Answer

Think you can help? Login to answer this question!