How do I prevent event bubbling in a Titanium Alloy view?
Asked Answered
C

3

6

In the documentation, it seems that you can prevent bubbling by passing an arguments to an click event on a text field:

http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.UI.TextField-event-click

Using their new Alloy framework, I have a textfield declared like so:

<TextField id='name' onClick='doStuff' />

and in my controller I have this function:

function doStuff(e) {
  alert('hello');
}

However, this element is wrapped in a container element which also has an onClick event, and I would like to prevent that one from firing when I click on the text field. how can I accomplish this?

Conal answered 28/2, 2013 at 20:7 Comment(0)
A
11

Try:

function doStuff(e){
    e.cancelBubble = true;
    alert('hello');
}
Antiphlogistic answered 1/3, 2013 at 15:34 Comment(0)
C
2

Suppose you have written this code in xml file:

<View id = “parent” onClick = “parentClicked”>
        <ImageView id=“sampleImage”  onClick= “childImageClicked”>
        </ImageView> 

</View>

Then

Try this in TSS :

“#sampleImage” : {

 bubbleParent : false,

}

or if you want to do it in Javascript :

function function_name(e){

    e.cancelBubble = true;
}

http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Event-property-cancelBubble

I hope this will work for you.

Connieconniption answered 5/8, 2016 at 11:42 Comment(0)
B
0

Perhaps a better way is to check the source property.

e.g. Lets say you have the following view:

<View id="parent" onClick="onParentClicked">
    <View id="child1" onClick="onChild1Clicked"/>
    <View id="child2" onClick="onChild2Clicked"/>
</View>

Solution 1: Use bubble parent property (Long)

You could do like the other answers and write in the tss file:

'#child1': {
    bubbleParent : false,
}
'#child2': {
    bubbleParent : false,
}

But this can become tedious with many child elements.

Solution 2: Use Javascript e.cancelBubble (Even longer)

In the javascript do:

function onChild1Clicked(e) {
    e.cancelBubble = true;
}
function onChild2Clicked(e) {
    e.cancelBubble = true;
}

Again this is tedious.

Solution 3: Use Javascript e.source (Best)

Just check what the source is on the parent event handler:

function onParentClicked(e) {
    if (e.source.id !== 'parent') {
        return;
    }
    alert("Parent clicked!");
}

This is much quicker. Especially when you have many child elements.

Bedpan answered 1/2, 2019 at 0:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.