vendredi 10 décembre 2021

How to add confirm addeventlistener to different view pages in rails

I have two different views: edit.html.erb and create.html.erb I want to add similar functionality onclick a checkbox on both the pages but want to avoid writing redundant code in both the files:

Currently what I am doing in both the files: In 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>

In 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>

Ideally I want to have a js file where both these events can be captured when clicking on either create or edit instead of writing this method individually on both files. What is a good way to do DRY here.

Aucun commentaire:

Enregistrer un commentaire