Last active
August 21, 2019 17:28
-
-
Save peterfication/d53dfe71349d65b5801df3df387d5ea4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This file has to be required before rails-ujs | |
// To use it change `data-confirm` of your links to `data-confirm-swal` | |
(function() { | |
const handleConfirm = function(element) { | |
if (!allowAction(this)) { | |
Rails.stopEverything(element) | |
} | |
} | |
const allowAction = element => { | |
if (element.getAttribute('data-confirm-swal') === null) { | |
return true | |
} | |
showConfirmationDialog(element) | |
return false | |
} | |
// Display the confirmation dialog | |
const showConfirmationDialog = element => { | |
const message = element.getAttribute('data-confirm-swal') | |
const text = element.getAttribute('data-text') | |
swal({ | |
title: message || 'Are you sure?', | |
text: text || '', | |
type: 'warning', | |
showCancelButton: true, | |
confirmButtonText: 'Yes', | |
cancelButtonText: 'Cancel', | |
}).then(result => confirmed(element, result)) | |
} | |
const confirmed = (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', element => { | |
Rails.delegate(document, 'a[data-confirm-swal]', 'click', handleConfirm) | |
}) | |
}).call(this) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment