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

133
Views
Esperando constantemente un clic (independientemente de los cambios en el DOM u otros clics)

El problema que tengo es con el jQuery datepicker. La ejecución de mi función ocurre con el clic de una fecha determinada. El problema ocurre cuando cambia el mes, luego se elimina todo el selector de fecha del DOM y aparece un nuevo selector de fecha.

Mi solución (mala solución) es esperar constantemente a que la flecha cambie DOM, cuando eso sucede, empiezo a ejecutar más el script. El mayor problema que tengo es el rendimiento, porque uso el intervalo.

ingrese la descripción de la imagen aquí

Este es mi ejemplo de una solución que funciona, pero apenas...

 $('#input-for-opening-datepicker').on('click', function(){ // In my attempt to solve the problem it is necessary to use an interval // because without it the program does not see the change of the month // and does not catch a click on the date. setInterval( function(){ const arrows = $('.datepick-arrows'); // If arrows exist in DOM, wait for the click if (arrows.length > 0){ arrows.on('click', function(){ // ... then wait for the date click to continue executing the code $('.datepick-month table tbody tr td a').on('click', function() { // Code... }); }); // If you do not click on the change of the month, and the date picker // is open then wait again for the click of a certain date because the // change of the month does not have to happen by the user. $('.datepick-month table tbody tr td a').on('click', function() { // Code... }); } }, 200); });

¿Cómo logro la ejecución del script sin usar un intervalo que afecte en gran medida el rendimiento?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

La conexión de controladores de eventos en respuesta a un evento no suele ser la mejor práctica, y conectarlos en un temporizador de intervalo definitivamente no es la mejor práctica. Su código vuelve a conectar repetidamente los eventos (incluso en los mismos elementos).

En cambio, dos opciones para ti:

Delegación de eventos

Si el selector de fecha no cancela la propagación (burbujeo) de los eventos de clic, puede usar la delegación de eventos:

 document.addEventListener("click", function(event) { const arrow = event.target.closest(".datepick-arrows"); if (arrow) { // Click on a datepicker arrow // ...do what you do on arrow click... return; } const month = event.target.closest(".datepick-month table tbody tr td a"); if (month) { // Click on a month // ...do what you do on month click... return; } });

MutationObserver

Si el selector de fecha detiene la propagación, el enfoque de delegación no funcionará. En ese caso, puede usar un MutationObserver para observar el selector de fecha que se agrega al DOM y conectar sus controladores (probablemente usando un WeakSet para recordar aquellos en los que sabe que ha conectado eventos).

 // A weak set of known date pickers const knownDatePickers = new WeakSet(); // The observer const observer = new MutationObserver(function(mutations) { // Or you could look through `mutations` for the datepicker const datePicker = document.querySelector("selector for the datepicker"); if (datePicker && !knownDatePickers.has(datePicker)) { knownDatePickers.add(datePicker); // ...hook up your datepicker events here... } }); observer.observe(document.documentElement, { attributes: false, childList: true, subtree: true });

O puede evitar la necesidad del WeakSet mirando las notas recién agregadas en el registro de mutación:

 const observer = new MutationObserver(function(mutations) { let added = null; let removed = null; for (const mutation of mutations) { for (const node of mutation.addedNodes) { if (node.matches && node.matches("selector for datepicker") { added = node; break; } } for (const node of mutation.removedNodes) { if (node.matches && node.matches("selector for datepicker") { removed = node; break; } } } if (added && added !== removed) { // If you *move* an element, it appears in // both `addedNodes` and `removedNodes` // `added` is a new datepicker, set up your event handlers } }); observer.observe(document.documentElement, { attributes: false, childList: true, subtree: true });

Las dos opciones enumeradas son direcciones a seguir, no soluciones de copiar y pegar. Deberá completar los espacios en blanco y modificar el código según sea necesario.

about 4 years ago · Juan Pablo Isaza 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!