在使用jquery_ujs
之前的Rails版本中,我们可以通过覆盖$.rails.allowAction
替换浏览器的确认弹出窗口,如这里所述。
从使用rails-ujs
的Rails 5.1 开始,不再可用$.rails.allowAction
。我们如何在Rails 5中使用Rails的默认确认,而无需切换回jquery_ujs
?
预先感谢。
我也面临着同样的挑战,我看上去更多。在此过程中我发现的内容可以在这里阅读:https://medium.com/store2be-tech/how-to-use-sweetalert2-for-your-rails-5-1-rails-5-1-rails-ujs-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使用)
您可以用Rails.confirm
覆盖它,例如。与咖啡本:
Rails.confirm = (message, element) ->
# your code
例如。要显示确认文本2秒:
WAITING_CLASS = "waiting-for-confirmation"
TIMEOUT = 2000
Rails.confirm = (message, element) ->
if element.classList.contains(WAITING_CLASS)
true
else
element.dataset.beforeConfirm = element.textContent
element.textContent = element.dataset.confirm
element.classList.add(WAITING_CLASS)
timeout TIMEOUT, ->
element.classList.remove(WAITING_CLASS)
element.textContent = element.dataset.beforeConfirm
false
请参阅:https://github.com/rails/rails/blob/master/comateview/app/assets/javascripts/rails-ujs/features/features/confirm.coffee
和 timeout
,只是一个简单的功能,它会倒入 setTimeout
参数:
var timeout = function(time, callback) {
setTimeout(callback, time)
}