Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent an action on a parent component from being called when I click on a child component?

Tags:

ember.js

I have the following bit of template in a project I'm working on:

<div class="item row" {{action "expandItem"}}>
  {{input type="checkbox" checked=isChecked}}
  {{item.name}}
</div>

The trouble I'm running into is that clicking the checkbox does not change its state. It does, however, fire the expandItem action. I'd like the behavior to be that clicking on the checkbox changes isChecked but clicking anywhere else in the div fires expandItem. How can I accomplish this?

EDIT: The question Stop click propagation from Ember action is very close, but the difference as I see it is that the child element in the other question is using the {{action}} helper, which can easily stop propagation with bubbles=false. In my case, I don't necessarily have a hook into how Ember's default Input Component bubbles the action

SECOND EDIT: I recreated exactly the behavior I'm seeing in this JSBin. You'll notice how the Input Component and the inline action helper behave differently. Hope this helps.

like image 678
brad_julian Avatar asked Feb 24 '16 05:02

brad_julian


People also ask

How do I prevent a parent's onclick event from firing when a child is clicked?

If you use event. stopPropagation() , sure it will stop any parent events from firing.

How do you stop event propagation from parent to child?

stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.

How do you stop child elements from inheriting parent element onclick in React?

By default when the onClick event of the child element is triggered, the event on the parent element would also get triggered, but the stopPropagation() method prevents this behavior.


1 Answers

Since Ember 1.13.3 you can do the following (the example does not use input helper and I would not recommend using it if possible):

Template:

<label onclick={{action "stopPropagation"}}>
    <input type="checkbox" checked={{checked}} 
           onchange={{action "check" value="target.checked"}}>
</label>

Component/controller:

actions: {
   check() {
      this.toggleProperty('checked');    
   },
   stopPropagation(event) {
      event.stopPropagation();
   }
}

You cannot just stop action from propagating with bubbles=false since in this case event.preventDefault is also called disabling default checkbox behavour.

Here is Ember Twiddle

like image 76
chekmare Avatar answered Sep 23 '22 02:09

chekmare