2017-08-28 134 views

回答

2

我遇到了同样的挑战,并且我更加注意了它。我一路上发现可以在这里读到: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) 
1

我还没有找到一个美丽的方式来调整到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使用的单击事件之前执行)