0

我使用 railsform_with作为远程表单。在提交之前,我想显示一个带有动态消息的自定义确认框。在确实确认该框后,我想最终提交表格。我想出了 'ajax:beforeSend' 事件处理程序:

const form = document.getElementById('assign_sessions_to_employees')
form.addEventListener(
  'ajax:beforeSend',
  (event) => {
    event.preventDefault();
    swal.fire({
      title: 'Are you sure ?',
      text: `You are about to spend ${expectedExpenditure()} credits.`,
      showCancelButton: true,
    }).then((result) => {
      if (result.isConfirmed) {
        console.log('submitting')
        Rails.fire(form, 'submit');
      }
    })
  }
)

这很好用,但是当我运行Rails.fire(form, 'submit');时,当我最终想提交重新触发的表单时'ajax:beforeSend',我陷入了循环。

使用 form_with 和 rails ujs 实现这种行为的正确方法是什么?

4

1 回答 1

0

如果您使用函数声明(也称为命名函数),您可以使用EventTarget.removeEventListener()删除事件处理程序:

function handleConfirmation(event){
  let form = event.target;
  event.preventDefault();
  swal.fire({
     title: 'Are you sure ?',
     text: `You are about to spend ${expectedExpenditure()} credits.`,
     showCancelButton: true,
  }).then((result) => {
     if (result.isConfirmed) {
       console.log('submitting');
       form.removeEventListener('ajax:beforeSend', handleConfirmation);
       Rails.fire(form, 'submit');
     }
    })
  }
}
const form = document.getElementById('assign_sessions_to_employees')
form.addEventListener('ajax:beforeSend', handleConfirmation);

另一种选择是在事件处理程序中设置一个数据属性:

const form = document.getElementById('assign_sessions_to_employees')
form.addEventListener(
  'ajax:beforeSend',
  (event) => {
    if (event.target.dataset.confirmed) { return };
    event.preventDefault();
    swal.fire({
      title: 'Are you sure ?',
      text: `You are about to spend ${expectedExpenditure()} credits.`,
      showCancelButton: true,
    }).then((result) => {
      if (result.isConfirmed) {
        console.log('submitting');
        form.dataset.confirmed = true;
        Rails.fire(form, 'submit');
      }
    })
  }
)
于 2021-10-12T12:48:32.993 回答