Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question about the passed Stimulus controller values #755

Open
titanve opened this issue Mar 15, 2024 · 3 comments
Open

Question about the passed Stimulus controller values #755

titanve opened this issue Mar 15, 2024 · 3 comments

Comments

@titanve
Copy link

titanve commented Mar 15, 2024

This is a quick question: Why should we only pass values in the element where we placed the data-controller?
Why we cannot place them in the child elements under the element where the data-controller is placed?

image

Thanks!

@marcoroth
Copy link
Member

Hey @titanve, the primary reason that speaks against this is that you could end up with more than value for the same controller and Stimulus Value, since you are allowed to place the same attribute on more than just the controller-element itself.

@marcoroth
Copy link
Member

With that being said, I think it would be neat to have a similar feature to the Stimulus Targets where you can define the same Stimulus Value more than once and get access to all the values in an array with the plural accessor.

So you could do something like:

<div data-controller="post">
  <article id="post_1" data-post-target="post" data-post-id-value="1"></article>
  <article id="post_2" data-post-target="post" data-post-id-value="2"></article>
  <article id="post_3" data-post-target="post" data-post-id-value="3"></article>
  <article id="post_4" data-post-target="post" data-post-id-value="4"></article>
</div>
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["post"]
  static values = {
    id: Number
  }

  connect() {
    this.idValue // => either `null` (since the data-attribute on the controller-element is not defined) or the first one it sees (`1`)
    this.idValues // => [1, 2, 3, 4]
  }
}

@titanve
Copy link
Author

titanve commented Mar 18, 2024

Hi @marcoroth

Is it possible to implement your suggestion? I would like to.

We would need to search down in the DOM tree, from where the data-controller="post" is placed, for any occurrence of data-post-*-value="some_value" and populate the array or arrays depending if we have more than one key value.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants