Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
Cómo agregar confirmar addeventlistener a diferentes páginas de vista en rieles

Tengo dos vistas diferentes: edit.html.erb y create.html.erb Quiero agregar una funcionalidad similar al hacer clic en una casilla de verificación en ambas páginas, pero quiero evitar escribir código redundante en ambos archivos:

Actualmente, lo que estoy haciendo en ambos archivos: en 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>

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

Idealmente, quiero tener un archivo js donde ambos eventos se puedan capturar al hacer clic en crear o editar en lugar de escribir este método individualmente en ambos archivos. ¿Cuál es una buena manera de hacer SECO aquí.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

Simplemente lo haría de la misma manera que lo hace Rails UJS: agregando un detector de eventos que apunte a elementos con un atributo 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>

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!