2
import { Controller } from "@hotwired/stimulus";
import consumer from "channels/consumer";

export default class extends Controller {
  static targets = ["users", "roomId"]

  connect() {

    this.subscription = consumer.subscriptions.subscriptions.find(subscription => 
    subscription.identifier === '{"channel":"RoomChannel"}');

    console.log("CONNECTED")

    console.log("Connected to room controller");
    console.log("Element: ", this.element);
    console.log("Users target: ", this.usersTarget);
    console.log("Room ID target: ", this.roomIdTarget);

    this.subscription.received = this.received.bind(this);


   }

}

HTML:

<div data-controller="room">
  <p>Joined users: <span data-target="users"></span></p>
  <p>Room ID: <span data-target="roomId"></span></p>
</div>

DEV TOOLS LOGS:

  1. CONNECTED
  2. Connected to room controller
<div data-controller="room">
  <p>Joined users: <span data-target="users"></span></p>
  <p>Room ID: <span data-target="roomId"></span></p>
</div>

AND 4)

Error connecting controller

Error: Missing target element "users" for "room" controller
Wordica
  • 2,427
  • 3
  • 31
  • 51
  • 2
    you're missing the controller name in the target declaration. Target and Value declarations now need the controller name. like `data-room-target="users"` – trh Apr 23 '23 at 14:08

1 Answers1

1

As per the Stimulus documentation - you must include the controller identifier in the target attribute name.

https://stimulus.hotwired.dev/reference/targets

<div data-controller="room">
  <p>Joined users: <span data-room-target="users"></span></p>
  <p>Room ID: <span data-room-target="roomId"></span></p>
</div>

I believe an older version of Stimulus did not require this, however the latest version does. The reason for this is so that you can have the same element targeted by multiple controllers without having name clashes.

LB Ben Johnston
  • 4,751
  • 13
  • 29