Hotwire Discussion

Stimulus not working with frames

so i render a turbo frame that has a button with stimulus action on it and the action is not working. it does work if i just put the code without the frame

frame

<%= turbo_frame_tag player do %>
  <% if player.game.started? %>
    <div class='spy-or-word' data-spy-target='spyOrWord'>
      <% if player.spy? %>
        spyyy
      <% else %>
        <%= player.game.word %>
      <% end %>
    </div>
    <button type='button' data-action='spy#toggle'>show/hide</button>
  <% end %>
<% end %>

stimulus controller

import { Controller } from "stimulus"

export default class extends Controller {
    static targets = ["spyOrWord"]

    toggle(e) {
        console.log("togle");
        if (this.spyOrWordTarget.classList.contains('show')) {
            this.spyOrWordTarget.classList.remove('show')

        } else {
            this.spyOrWordTarget.classList.add('show')

        }
    }
}

Where do you define data-controller="spy"?.

FYI, you could simplify your controller with:

import { Controller } from "stimulus"

export default class extends Controller {
    static targets = ["spyOrWord"]

    toggle(e) {
        this.spyOrWordTarget.classList.toggle('show')
    }
}

the issue was with the data-contorller as tleish pointed out, i put th data controller on the frame and it worked

<%= turbo_frame_tag "player_kind", data: {controller: "spy"} do %>
  <% if game.started? %>
    <div class='spy-or-word-wrapper'>
      <div class='spy-or-word' data-spy-target='spyOrWord'>
        <span>
          <% if player.spy? %>
            <%= t("spy") %>
          <% else %>
            <%= game.word %>
          <% end %>
        </span>
      </div>
      <button class='btn hide-btn' type='button' data-action='spy#toggle'>show/hide</button>
    </div>
  <% end %>
<% end %>