【发布时间】:2021-10-11 08:53:53
【问题描述】:
我使用 rails form_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 实现此行为的正确方法是什么?
【问题讨论】:
-
使事件处理程序成为命名函数而不是箭头函数。这样你就可以remove the handler。另一种技术是在用户确认时设置一个数据属性或向表单元素添加一个类,并在函数顶部放置一个保护语句,如果它存在则返回。 medium.com/beginners-guide-to-mobile-web-development/…
-
@max 你能举个例子吗?如果我在这种情况下删除侦听器,那么如果稍后提交表单,我将无法再显示确认...
标签: javascript ruby-on-rails rails-ujs form-with