发生了什么?
- 表单已提交
- rails-ujs 禁用按钮(
data-disable-with 行为)
- 表单请求成功
- rails-ujs 重新启用按钮
- turbolinks-rails 向重定向位置发出请求(这可能是一个缓慢的请求,使按钮处于启用状态)
解决方案
我们需要在第 4 步之后重新禁用该按钮。为此,我们将监听ajax:success 事件,并使用setTimeout 禁用它。这确保了它会在 Rails 完成它的操作之后被禁用。 (您可以使用requestAnimationFrame 代替setTimeout,但它没有得到广泛支持。)
为防止按钮在禁用状态下被缓存,我们将在它被缓存之前重新启用它。 (注意使用one 而不是on 以防止缓存前处理程序执行多次。)
我注意到您使用的是 jQuery 和 jquery-ujs,因此我将在下面的代码中使用这些库中的函数。在你的主 JavaScript 文件中包含这个。
jquery-ujs
;(function () {
var $doc = $(document)
$doc.on('submit', 'form[data-remote=true]', function () {
var $form = $(this)
var $button = $form.find('[data-disable-with]')
if (!$button.length) return
$form.on('ajax:complete', function () {
// Use setTimeout to prevent race-condition when Rails re-enables the button
setTimeout(function () {
$.rails.disableFormElement($button)
}, 0)
})
// Prevent button from being cached in disabled state
$doc.one('turbolinks:before-cache', function () {
$.rails.enableFormElement($button)
})
})
})()
rails-ujs / jQuery
;(function () {
var $doc = $(document)
$doc.on('ajax:send', 'form[data-remote=true]', function () {
var $form = $(this)
var $button = $form.find('[data-disable-with]')
if (!$button.length) return
$form.on('ajax:complete', function () {
// Use setTimeout to prevent race-condition when Rails re-enables the button
setTimeout(function () {
$button.each(function () { Rails.disableElement(this) })
}, 0)
})
// Prevent button from being cached in disabled state
$doc.one('turbolinks:before-cache', function () {
$button.each(function () { Rails.enableElement(this) })
})
})
})()
rails-ujs / vanilla JS
Rails.delegate(document, 'form[data-remote=true]', 'ajax:send', function (event) {
var form = event.target
var buttons = form.querySelectorAll('[data-disable-with]')
if (!buttons.length) return
function disableButtons () {
buttons.forEach(function (button) { Rails.disableElement(button) })
}
function enableButtons () {
buttons.forEach(function (button) { Rails.enableElement(button) })
}
function beforeCache () {
enableButtons()
document.removeEventListener('turbolinks:before-cache', beforeCache)
}
form.addEventListener('ajax:complete', function () {
// Use setTimeout to prevent race-condition when Rails re-enables the button
setTimeout(disableButtons, 0)
})
// Prevent button from being cached in disabled state
document.addEventListener('turbolinks:before-cache', beforeCache)
})
请注意,这将禁用按钮,直到下一页加载到所有带有 data-disable-with 按钮的 data-remote 表单上。您可能希望更改 jQuery 选择器以仅将此行为添加到选定的表单。
希望有帮助!