Multiple targets with the same name

I have a list of items, and each one has a link to click to edit it. I am using stimulus to make the edit “modal” form visible when they click that edit link. The id of what is going to be edited is present as an id= on the corresponding link tag of the list

So, the edit link looks like this:

<td><a data-action="click->content#edit" data-target="content.editBtn" id="<%= url_for(content) %>")>Edit</a></td>

And the idea is that the content#edit action in the stimulus controller examines the and locates the id of it and uses that to edit the right row.

However the problem I am having is, I think, that as a result all the rows of this list have a data-target with the same name and the wrong one (the first one?) gets bound to the target…

However if I wanted to make each data-target different by e.g. appending the id to it, now I have a long list of targets in the controller.js so that doesn’t make sense.

Phew, I hope you followed that. What’s the right way to handle?

Addressed on StackOverflow here.

On SO you accepted an alternative approach but to give you a hint for your actual stimulus problem, when the data-action is fired an event object is passed to your action method and you can access that <a> tag simply like this:

// in content controller
function edit(event) { console.log(event.target); }
3 Likes

Yeah the problem was this… there are numerous rows, and each would have the same named target. If I place my controller as an ancestor to that table, then the named target corresponding to the action would get called. So the scoping is pretty sophisticated.

However the tag that I wanted to modify (to make the modal become visible) was not an ancestor to that list and so the same controller would not detect a target in that modal dialog box html. So within stimulus it was hard to make it work. I did manage it but it was a little tricky and in the end the ‘remote:true’ approach was cleaner and much simpler

This should be marked as a correct answer.

This answer helped me a lot.

I put an element like a <td data-name='jeff' data-age='27'>

and on my event

add(event) {
  people.push({
    name: event.currentTarget.dataset.name,
    age: event.currentTarget.dataset.age
  })
}