在使用jquery_ujs的Rails 5.1之前的版本中,我们可以通过覆盖$.rails.allowAction来替换浏览器的确认弹出窗口,正如here所解释的那样。
从使用rails-ujs的Rails 5.1+开始,$.rails.allowAction不再可用。在Rails5中,我们如何用自己的确认覆盖Rails的默认确认,而不必切换回jquery_ujs
提前谢谢。
发布于 2017-12-02 23:25:51
我也遇到了同样的挑战,我对此进行了更深入的研究。我一路上发现的东西可以在这里读到: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)发布于 2017-11-10 20:47:31
我还没有找到一个很好的方法来调整到rails_ujs中,所以我使用了这个变通方法(使用CoffeeScript):
```javascript$(文档).on 'mousedown',‘adata confirm’,(e) ->
e.preventDefault()
链接= $(e.target)
message = link.data‘确认’
modal = $('.modal.confirmation')
Modal.find(‘.content’)消息(.text)
approve = modal.find('.approve')
approve.attr('data-method',link.data('method'))
approve.attr('href',link.attr('href'))
modal.modal('show')
Mousedown事件允许首先执行我的事件处理程序(它位于rails_ujs使用的click事件之前)
发布于 2019-03-30 09:14:28
您可以使用Rails.confirm覆盖它,例如使用CoffeeScript:
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和timeout,以及一个简单的倒置setTimeout参数的函数:
var timeout = function(time, callback) {
setTimeout(callback, time)
}https://stackoverflow.com/questions/45923864
复制相似问题