如何将confirm-addeventlistener添加到rails中的不同视图页面



我有两个不同的视图:edit.html.erb和create.html.erb我想在点击两个页面上的复选框时添加类似的功能,但希望避免在两个文件中写入冗余代码:

目前我在这两个文件中所做的工作:在create.html.erb 中

<script>
function onclick (event) {
var message = 'Are you sure ?';
confirm(message) || event.preventDefault();
}
var elem = document.getElementById('create');
elem.addEventListener('click', onclick);
</script>

在edit.html.erb 中

<script>
function onclick (event) {
var message = 'Are you sure ?';
confirm(message) || event.preventDefault();
}
var elem = document.getElementById('edit');
elem.addEventListener('click', onclick);
</script>

理想情况下,我希望有一个js文件,当单击create或edit时,可以在其中捕获这两个事件,而不是在这两个文件上单独编写此方法。在这里干什么是好方法。

我只想用与Rails UJS相同的方式来做这件事——添加一个针对具有data-confirm属性的元素的事件侦听器:

function handleConfirm(e){
if (!event.target.matches('[data-confirm]')){ return; };
const attr = e.target.dataset.confirm;
const message = attr.length > 0 ? attr : 'Are you sure ?';
window.confirm(message) || e.preventDefault();
}
document.addEventListener('click', handleConfirm);
<button>No confirmation</button>
<button data-confirm>Standard message</button>
<button data-confirm="REALLY???!!">A button with a custom text</button>

最新更新