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?
@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.targetreturns 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
Most helpful comment
@bihnkim