DEV Community

Cover image for My beloved Stimulus.js cheat sheet
Eric The Coder
Eric The Coder

Posted on

My beloved Stimulus.js cheat sheet

Hi, I use Stimulus once in awhile in my Rails app. I made this little cheat sheet to help me remember the basic concepts.

HTML atributes


<!-- Initialize/name data controller -->
<div data-controller="hello">

<!-- Reference map a DOM field -->
<input data-hello-target="name">

<!-- Reference value -->
<div data-hello-url-value="/test">

<!-- Reference class -->
<div data-hello-loading-class="search--busy">

<!-- On event -> Call controller#method -->
<button data-action="click->hello#sayHello">

Enter fullscreen mode Exit fullscreen mode

Javascript

// use stimulus library  
import { Controller } from "stimulus"

// Extends Controller base class
export default class extends Controller {

// Link references map DOM fields
static targets = [ "name", "output" ]

// use map DOM field 
sayHello() {
  this.outputTarget.textContent = 
      `Hello, ${this.nameTarget.value}!`
  }
}

// Multiple Map of the same name
this.nameTargets

// Iterations
showAllNames() {
    this.nameTargets.forEach((element, index) => {
      console.log(`${index}. ${element.value}`)
    })
  }

// Check if a map exist 
this.hasNameTarget // return true or false

// Ref current element (event->controller#action)
this.element.innerHTML

// Reference Values
static values = { url: String }
console.log(this.urlValue)

// Reference Classes
static classes = [ "loading" ]

// Add class name to current element
this.element.classList.add(this.loadingClass)

// Remove class name to current element
this.element.classList.remove(this.loadingClass)

// Event object
sayHello(event) {
    // cancel normal flow
    event.preventDefault()

    // Stop event before it bubble up to parent
    event.stopPropagation()

    // Event element
    event.target.textContent
}

// Lifecycle Callbacks methods

initialize() // Once, when the controller is first instantiated
connect() // Anytime the controller is connected to the DOM
disconnect() // Anytime the controller is disconnected from the DOM
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
megatux profile image
Cristian Molina •

Thanks for this! For accessing another controller do you use this.application.getControllerForElementAndIdentifier() or this.element["something"] = this in connect() or something else?