HomeCloud ComputingIntro to Hotwire: HTML over the wire

Intro to Hotwire: HTML over the wire



In Stimulus, you employ HTML attributes to attach parts to “controllers,” that are chunks of JavaScript performance. For instance, if we needed to supply a clipboard copy button, we might do one thing like this:

A fragile, native berry with massive, comfortable leaves.

Discover the data-contoller attribute. That hyperlinks the ingredient to the clipboard controller. Stimulus makes use of a filename conference, and on this case, the file can be: clipboard_controller.js, with contents one thing like this:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {

  // Connects to data-clipboard-target="supply" 
  // and data-clipboard-target="suggestions"
  static targets = [ "source", "feedback" ]

  // Runs when data-action="click->clipboard#copy" is triggered
  copy() {
    // 1. Get textual content from the "supply" goal
    const textToCopy = this.sourceTarget.textContent
    
    // 2. Use the browser's clipboard API
    navigator.clipboard.writeText(textToCopy)

    // 3. Replace the "suggestions" goal to inform the consumer
    this.feedbackTarget.textContent = "Copied!"

    // 4. (Optionally available) Reset the button after 2 seconds
    setTimeout(() => {
      this.feedbackTarget.textContent = "Copy Identify"
    }, 2000)
  }
}

The static goal member supplies these parts to the controller to work with, primarily based on the data-clipboard-target attribute within the markup. The controller then makes use of easy JavaScript to carry out the clipboard copy and a timed message to the UI.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments