Home > other >  How to add confirm addeventlistener to different view pages in rails
How to add confirm addeventlistener to different view pages in rails

Time:12-13

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.

CodePudding user response:

I would just do it the same way that Rails UJS does - by adding an event listener that targets elements with a data-confirm attribute:

function handleConfirm(e){
  if (!event.target.matches('[data-confirm]')){ return; };
  const attr = e.target.dataset.confirm;
  const message = attr && 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>

  • Related