Last active
August 24, 2023 15:45
-
-
Save mithicher/8399a5d2ddd4cc691b8eee751dacf06c to your computer and use it in GitHub Desktop.
SweetAlert2 Confirm Deletion
This file contains 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
// Usage: | |
// <x-button type="button" wire:confirm="delete(1)">Confirm Test</x-button> | |
document.addEventListener('livewire:init', () => { | |
Livewire.directive('confirm', ({ el, directive, component, cleanup }) => { | |
let content = directive.expression | |
// This regex splits the method given: eg. "delete(1)" to ['delete(1)', 'delete', '1'] | |
const regex = /([a-zA-Z_][a-zA-Z0-9_]*)\((['"][^'"]*['"]|\d+)\)/; | |
const matches = directive.expression.match(regex); | |
let onClick = e => { | |
Swal.fire({ | |
title: 'Are you sure?', | |
text: "You won't be able to revert this!", | |
showCancelButton: true, | |
confirmButtonColor: '#d33', | |
cancelButtonColor: '#aaa', | |
confirmButtonText: 'Yes, delete it!' | |
}).then((result) => { | |
if (result.isConfirmed) { | |
component.$wire.call(matches[1], matches[2]) | |
} | |
}); | |
} | |
el.addEventListener('click', onClick, { capture: true }) | |
cleanup(() => { | |
el.removeEventListener('click', onClick) | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment