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.
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?
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:
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.