Stimulus: Cannot access actioned-element from event/action method

Created on 26 May 2018  路  3Comments  路  Source: hotwired/stimulus

I have the follow scenario:

JS

export default class extends Controller {
  public show(event) {
    // event is the MouseEvent
    // Have to no way in here to find the element that the action came from.
    // I'm trying to get the element's data-random's value (see below).
  }
}

HTML

<body data-controller="foo">
  ...
  <button data-action="foo#show" data-random="value_for_controller">
    <i class="qrcode icon"></i>
  </button>
</body>

The button is 90% covered by the icon element, eg:
image

If I click on the icon (the <i> element), my Foo controller will receive the event in the show function. However, the target of the event is the <i> element. I was expecting it to be the button element since that's where the data-action sits.

If this is intended behavior, what's the best way to get the button element (or the element that action was declared on)?

Most helpful comment

event.currentTarget will always be the element with the action definition:

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

-- https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

All 3 comments

Looking through the source, this looks like intended behavior...but I鈥檇 still like to get the element that the action is defined on. Since we can鈥檛 modify the event, maybe we can pass the element along with the event when invoking the method on the controller? https://github.com/stimulusjs/stimulus/blob/master/packages/%40stimulus/core/src/binding.ts#L47

event.currentTarget will always be the element with the action definition:

Identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

-- https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

Thanks @javan! 馃檱

It's weird that currentTarget was showing as null when I print it out the event on console. But you're right, it evaluates to the button in code.

Was this page helpful?
0 / 5 - 0 ratings