简体   繁体   中英

Javascript code refactor to use in Stimulus controller

How to refactor JS code like this:

const fileInput = document.getElementById('input');
const p = document.querySelector('p');
fileInput.onchange = () => {
  const selectedFiles = [...fileInput.files];
  p.textContent = selectedFiles.map(s => s.size).join(', ');
}

to make it work in rail's Stimulus? I have very little experience with JS and want to have one or two examples of implementing JS code in Stimulus controllers, so I have material to refactor other cases on my own. Much thanks.

One possible solution:

<div data-controller="file">
  <input type="file" data-file-target="input" data-action="change->file#displayText" id="my-input">
  <output data-file-target="text" for="my-input"></output>
</div>
// filename_controller.js

// Connects to data-controller="file"
export default class extends Controller {
  static targets = ["input", "text"]
  
  displayText() {
    const selectedFiles = [...thisInputTarget.files];
    this.textTarget.textContent = selectedFiles.map(s => s.size).join(', ');
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM