Event.currentTarget issue

I was debugging the problem in my javascript code with variable setting wrong. After a little research, I found out that the variable was not populated because it takes its value from an event property that was not there. In this case, it was inferring its value from event.currentTarget, which was strangely null.

So, I'm a little confused. I have always though, this event.currentTarget always pointed to any element containing a listener that triggered the event. So, under what circumstances will event.currentTarget actually be null?

+3


source to share


1 answer


Ok, I finally figured it out.

The problem was how the event was handled. As you can see below, the event object itself had to be handled by more than its corresponding handler function; it will also be handled by another function that was only called when the AJAX call that was made in the handler returned successfully. However, as soon as the success function is executed under the AJAX call, the event object loses some of its context, namely its currentTarget property. I guess the reason this is because we don't get directly into the scope of the handler when the browser starts executing the code in the success function.



$('#element').click(function(e) {

    // bunch of lines of code here

    $.ajax({
       type: 'POST',
       url: // url,
       ...,
       success: function(response) {

           // more lines of code here

           callAnotherFunction(e);
           // When we invoke the above function, we pass the event in as a 
           // parameter, but the event has already lost some of its context
           // due to scope change.
       }
    });

})

      

+3


source







All Articles