Connected and Disconnected Target Callbacks with Stimulus

In a previous article I wrote about the change callbacks for the Values API. This time I want to highlight the Connect and Disconnect callbacks for targets.

A quick recap on targets: targets lets you reference important elements by name. They are set up like so:

<div data-controller="eggs">
  <h2>Eggs</h2>

  <ul>
    <li data-eggs-target="item">🥚</li>
  </ul>
</div>

Then in your Stimulus controller:

// app/javascript/controllers/eggs_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["item"];
  // …
}

Keep track of new targets being added

Let’s assume above eggs list only allows you to add more eggs, nothing else. 🐣 The HTML could look like this:

<div data-controller="eggs">
  <h2>Eggs <span data-eggs-target="count"></span></h2>

  <ul data-eggs-target="list">
    <li data-eggs-target="item">🥚</li>
  </ul>

  <button data-action="eggs#add">Add</button>
</div>

Let’s quickly extend the above controller with the add() feature:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["list", "item"];

  add() {
    this.listTarget.insertAdjacentHTML("beforeend", `<li data-eggs-target="item">🥚</li>`);
  }
}

Easy enough! Let’s write the code to show the number of eggs in the list.

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["list", "item", "count"];

  // …

  itemTargetConnected() {
    this.#updateItemCount();
  }

  itemTargetDisconnected() {
    this.#updateItemCount();
  }

  // private

  #updateItemCount() {
    this.countTarget.textContent = `(${this.itemTargets.length})`;
  }
}

Preview of the controller, showing adding the egg-emoji to a list

Notice how the <span data-eggs-target="count"></span> gets updated with the number of eggs (targets) whenever a new one is added to the list. Also notice how it is also already updated upon the controller connect lifecycle method (ie. when the page is loaded).

Yet another small, but really useful lesser known feature of Stimulus. How have you used target callbacks? Let me know.

Get UI & Product Engineering Insights for Rails Apps (and product updates!)

Published at . Last updated at . Have suggestions or improvements on this content? Do reach out.

UI components for Ruby on Rails apps

$ 129 one-time
payment

Get Access
  • One-time Payment

  • Access to the Entire Library

  • Built for Ruby on Rails (inc. Rails 8)

  • Designed with Tailwind CSS and Enhanced with Hotwire

  • Updates for 12 months