hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.67k stars 420 forks source link

Repeating targets with the same name #165

Closed pitosalas closed 6 years ago

pitosalas commented 6 years ago

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?

danielcompton commented 6 years ago

I think you may want each row to have its own controller? Then the click would go to that controller. Alternatively you could look for the right target by walking up the chain from the event’s target, but that feels a bit dirty.

There may be more idiomatic ways though, I don’t have a ton of Stimulus experience.

EDIT: Looks like you also saw this discussion about Binding events to repeating elements

pitosalas commented 6 years ago

I considered each row with its own controller, but that seems quite ugly. Similarly is having a duplicate of the modal form with each row, also quite ugly.

The problem as I see it for the example that you link to is that the data-target is the same for each row. It would seem that this would confuse the controller, unless the data-action that triggers is tied to the particular (duplicated) instance of the data-controller, and somehow the context that is established resolves to the particular corresponding data-target.

I should try that if you think that's the right way to go.

pitosalas commented 6 years ago

I solved it but it seems I have to leave Stimulus in order to be able to address the html for the modal form. If you want I will explain it here. This is not an issue with stimulus per-se. Either there's a way to do this within Stimulus, or it's fine to sometime use old fashioned querySelector etc to address a bit of html. If there's a better way to do this, I'd love to hear it.

javan commented 6 years ago

Closing in favor of discussing on https://discourse.stimulusjs.org. Feel free to start a new thread.