A Stimulus component example

This one is using the planned new APIs for values and classes.

HTML

<script src="https://cdn.jsdelivr.net/gh/borama/stimulus@3e9d54b06bf3dd0d654c140b653c2a731445e45a/stimulus.umd.js"></script>
<!-- this works only in Stimulus 2.0 (not released yet) -->

<div data-controller="conversion" data-conversion-rates-value="{&quot;EUR&quot;: 0.881709, &quot;GBP&quot;: 0.798940, &quot;AUS&quot;: 1.435456, &quot;IND&quot;: 75.499926}" data-conversion-over1000-class="emphasize-big-number">
  $ <input data-conversion-target="input" type="text" data-action="keyup->conversion#calculate">
  = <span data-conversion-target="converted"></span>
</div>

CSS

.emphasize-big-number {
  font-weight: bold;
  color: red;
}

JavaScript

// This is an example of the new values & classes APIs that will be released (probably) in Stimulus 2.0.
// See https://dev.to/borama/a-few-sneak-peeks-into-hey-com-technology-v-stimulus-enhancements-gea.


const application = Stimulus.Application.start()

application.register("conversion", class extends Stimulus.Controller {
  // see https://stimulusjs.org/handbook/installing#using-without-a-build-system for explanation of this syntax
  static get targets() {
    return ["input", "converted"]
  }
  
  static get values() {
    return {
      rates: Object
    }
  }
  
  static get classes() {
    return ["over1000"]
  }
  
  calculate() {
    // emphasize big input numbers (over 1000)
    const value = this.inputTarget.value
    this.inputTarget.classList.toggle(this.over1000Class, value >= 1000.0)   

    // calculate and show all conversions
    let output = ""
    for (const prop in this.ratesValue) {
      const convertedValue = parseFloat(this.ratesValue[prop]) * parseFloat(value)
      output += `${prop} ${convertedValue.toFixed(2)}, `
    }
    this.convertedTarget.textContent = output
  }
})