Automate Value Changes
Let's learn about how to automate value changes.
We'll cover the following...
We'll cover the following...
Automating Value Changes
Another useful feature of the Stimulus Values API is that it includes a callback method called <value name>Changed
, which is automatically called after a Stimulus value is changed. In other words, we could rewrite our toggle controller as follows:
Press + to interact
import { Controller } from "stimulus"export default class FavoriteToggleController extends Controller {static targets = ["elementToHide", "elementWithText"]elementToHideTarget: HTMLElementelementWithTextTarget: HTMLElementstatic values = { visible: Boolean }visibleValue: booleantoggle(): void {this.flipState()}flipState(): void {this.visibleValue = !this.visibleValue}visibleValueChanged(): void {this.updateHiddenClass()this.updateText()}updateHiddenClass(): void {this.elementToHideTarget.classList.toggle("hidden", !this.visibleValue)}newText(): string {return this.visibleValue ? "Hide" : "Show"}updateText(): void {this.elementWithTextTarget.innerText = this.newText()}}
Now, the flipState()
method automatically causes visibleValueChanged
to ...