Stimulus: How to pass arguments through actions?

Created on 19 Jan 2018  路  6Comments  路  Source: hotwired/stimulus

For the slideshow example:

If I wanted to "jump" to the second image and would like to implement a "jump" action, I need to pass in the index of the clicked image. How can this be done?

Most helpful comment

@bihnkim

<div data-action="jump" data-slide-index="0">Open First slide</div>
jump(event) {
  const element = event.target
  this.targets.findAll('slides')[element.dataset.slideIndex]
  // next your logic to switch slides
}

All 6 comments

@bihnkim

<div data-action="jump" data-slide-index="0">Open First slide</div>
jump(event) {
  const element = event.target
  this.targets.findAll('slides')[element.dataset.slideIndex]
  // next your logic to switch slides
}

You could also write it like this

javascript jump(_event, element) { this.targets.findAll('slides')[element.dataset.slideIndex] // next your logic to switch slides }

Those are both reasonable options. Action methods are essentially just event handlers and there isn't a way to pass additional arguments to them.

Im having some issues with the example provided by @adrianholovaty.
If you have an element inside the action element, then _event.target returns the nested element instead in safari.
Also element is just undefined.

This jsbin shows the issues: http://jsbin.com/xiyuho/edit?html,js,console,output

@askehansen element as the second argument of your function was available in Stimulus 0.9 but this has been removed in 1.0. You must use now even.target

about safari if you look at the properties of event.targeton both browser they are the same

http://jsbin.com/nasopusali/1/edit?html,js,console,output

event.target returns the nested element

Use event.currentTarget to get the action element. Some related discussion here: https://discourse.stimulusjs.org/t/is-controller-scope-element-safe-to-use/109/9

Was this page helpful?
0 / 5 - 0 ratings

Related issues

paulozoom picture paulozoom  路  4Comments

saneef picture saneef  路  4Comments

savroff picture savroff  路  4Comments

joeybeninghove picture joeybeninghove  路  4Comments

incompletude picture incompletude  路  3Comments