在5.1之前的Rails版本中,使用jquery_ujs
,我们可以通过覆盖$.rails.allowAction
替换浏览器的确认弹出框,如here所述。Rails 5.1:如何覆盖rails-ujs中的allowAction以使用自定义确认对话框
从Rails 5.1+开始,它使用rails-ujs
,$.rails.allowAction
不再可用。我们如何在Rails 5中覆盖Rails的默认确认,而无需切换回jquery_ujs
?
在此先感谢。
在5.1之前的Rails版本中,使用jquery_ujs
,我们可以通过覆盖$.rails.allowAction
替换浏览器的确认弹出框,如here所述。Rails 5.1:如何覆盖rails-ujs中的allowAction以使用自定义确认对话框
从Rails 5.1+开始,它使用rails-ujs
,$.rails.allowAction
不再可用。我们如何在Rails 5中覆盖Rails的默认确认,而无需切换回jquery_ujs
?
在此先感谢。
我遇到了同样的挑战,并且我更加注意了它。我一路上发现可以在这里读到:https://medium.com/store2be-tech/how-to-use-sweetalert2-for-your-rails-5-1-rails-ujs-confirms-without-jquery-8a5b516b2a1
在这里,最终的解决方案:
(function() {
var handleConfirm = function(element) {
if (!allowAction(this)) {
Rails.stopEverything(element)
}
}
var allowAction = function(element) {
if (element.getAttribute('data-confirm-swal') === null) {
return true
}
showConfirmationDialog(element)
return false
}
// Display the confirmation dialog
var showConfirmationDialog = function(element) {
var message = element.getAttribute('data-confirm-swal')
var text = element.getAttribute('data-text')
swal({
title: message || 'Are you sure?',
text: text || '',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes',
cancelButtonText: 'Cancel',
}).then(function(result) {
confirmed(element, result)
})
}
var confirmed = function(element, result) {
if (result.value) {
// User clicked confirm button
element.removeAttribute('data-confirm-swal')
element.click()
}
}
// Hook the event before the other rails events so it works togeter
// with `method: :delete`.
// See https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts/rails-ujs/start.coffee#L69
document.addEventListener('rails:attachBindings', function(e) {
Rails.delegate(document, 'a[data-confirm-swal]', 'click', handleConfirm)
})
}).call(this)
我还没有找到一个美丽的方式来调整到rails_ujs,所以我想出了这个解决方法(使用CoffeeScript的):
```
$(document).on 'mousedown', 'a[data-confirm]', (e) ->
e.preventDefault()
link = $(e.target)
message = link.data 'confirm'
modal = $('.modal.confirmation')
modal.find('.content').text(message)
approve = modal.find('.approve')
approve.attr('data-method', link.data('method'))
approve.attr('href', link.attr('href'))
modal.modal('show')
```
Mousedown事件允许我的事件处理程序首先执行(它在rails_ujs使用的单击事件之前执行)