JavaScript 修改 rails-ujs 的默认行为

zhongsheng · November 06, 2019 · 5120 hits

<%= link_to "Dangerous zone", dangerous_zone_path,
  data: { confirm: 'Are you sure?' } %>

上面 rails erb 代码会生成一个链接,点击链接会跳出一个浏览器自带的 confirm 对话。 虽然有点不好看,不友好,但勉强能用. 直到有一天我在微信内打开页面发现这个对话框的取消选项变成了关闭网页,一点就关闭了页面。

在网上各种方法都比较老,不适用于 rails 6 和 webpacker. 自己看了一下 ujs 的源码,下面是我的解决方案:


import Rails from '@rails/ujs'
Rails.start()
// 覆盖原来的confirm
Rails.confirm = function(mes,element){
    // 不再跳出confirm对话框
    element.setAttribute('data-anwsered', 'false')
    return true
}

document.addEventListener('confirm', (event)=>{
    let element = event.target
    if(element.getAttribute('data-anwsered') == 'true'){
        return true
    }

    $.confirm({
        title: '请确认!',
        content: element.getAttribute('data-confirm'),
        closeIcon: true,
        buttons: {
            confirm: {
                text: '确定',
                btnClass: 'btn-red',
                action: function(){
                    element.setAttribute('data-anwsered', 'true')
                    // Rails.fire(element, 'rails.click')
                    // 重新触发点击的动作
                    element.click()
                }
            },
            cancel: {
                text: '取消',
                action: function(){
                }
            }
        }
    })
    // 很重要
    event.preventDefault()
})


主要思路就是覆盖原来的 confirm, 使用 jquery-confirm 给按钮添加状态。 通过这个状态来判断是否要继续下面的动作。

希望对大家有帮助。

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.