ruby-on-rails 重构表单字段和Stimulus JS,以便不重复:每个表单字段执行一次数据操作

1rhkuytd  于 2023-05-02  发布在  Ruby
关注(0)|答案(1)|浏览(89)

我有以下表格

<%= 
  form_for(
    model,
    html: {
      :'data-controller' => 'enable-submit-button-if-fields-changed'
    }
  ) do |form|
%>
  <%= form.text_field(:title, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%= form.text_area(:description, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%= form.file_field(:picture, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%= form.check_box(:delete_image, :'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit') %>
  <%#= other input fields... %>
<% end %>

和以下Stimulus JS控制器

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="enable-submit-button-if-fields-changed"
export default class extends Controller {
  connect() {
    this.element.querySelector('input[type=submit]').disabled = true;
  }

  enableSubmit() {
    this.element.querySelector('input[type=submit]').disabled = false;
  }
}

当输入字段发生变化时,它们可以启用提交按钮。
正如您在表单中看到的,我为每个输入字段添加了一次:'data-action' => 'input->enable-submit-button-if-fields-changed#enableSubmit'
什么是重构的方法,所以不重复:'data-action'一次为每个字段e。g.在表单上声明:'data-controller' => 'enable-submit-button-if-fields-changed',并(通过Stimulus)使其所有内部输入字段在更改时启用JS提交按钮?或者,我应该继续为每个字段重复:'data-action'一次吗?

相关问题