在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使用的單擊事件之前執行)