Skip to content
Advertisement

Javascript event listener problems

Supposing we have :

    //Some vars

function initialSetup(date){
    // Call to some functions
}

function populateCalendar(date){
    // Call to several function. Task : build and populate a calendar with the date

    awesomeFunction() // Have to set click event listener
    
    // If the function call purpose was detected as an update, return value
}

function awesomeFunction(){
    // For each day in the calendar, if there is a click, set the displayed date as the correct month, then rebuild the calendar
    $(".notInTheMonth").each(function(){
        $(this).click(function(e){
            //Some process
            //Changing date
            populateCalendar(processedDate)
            updateCalendar(processedVar)    
            //Some another process
        });
    });
}

function updateCalendar(updated){
    // Jquery transition from the old calendar to the new
    // Will put the content of the updated var to replace the content in the table calendar
}

When the calendar is updated, the event will not be replaced, so after a click event in the calendar, it will update one time but will not re-put the event listener provided by awesomeFunction.

So what’s the problems ?

Advertisement

Answer

You can use event delegation:

$(document).on('click', '.notInTheMonth', function() {
   // Your event handler here
});

When you attach an event listener to an element, the listener exist as long as this element exists in the DOM. So, when you update the calendar, these elements are deleted, so the event listener attached to them too.

With event delegation, you are setting a delegate (a static element like document) that is responsible for listening to any bubbled event from the type of elements you have specified (any element with class notInTheMonth)

Check this

EDIT

If you build the calendar and set event listeners, every time, make sure that the calendar has finished it’s building process and then attach the event listeners.

1) Build the calendar

2) Make sure the calendar elements exist in the DOM and then attach listeners

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement