Event Listener and AJAX asynchronous variable

I have a question, perhaps a very simple one, but whatever. When you register an event listener inside an asynchronous function, I believe that all values โ€‹โ€‹inside this function will be non-existent when the function runs it.

However, the event listener, as shown in the code below, can still access the values variable, how can I do this? Is the variable stored inside the event listener somehow?

 $.ajax({ type: "GET", cache: false, url: "/whatever", success: function(data) { var values = ["Some Values", "Inside this Object"]; $("#id :checkbox").click(function() { var allValues = []; $('#id3 :checked').each(function() { allValues.push($(this).val()); }); $("#id2").val(allValues); callMe.init(values,allValues); }); } }); 
+4
source share
2 answers

This is due to closure. The function โ€œclosesโ€ all variables in its lexical domain, which means that it retains access to them as soon as the function in which it was defined returns.

In your specific example, values are in scope when the function specified in click defined, so it will remain available even after success completed.

Here you will find much more information:

+2
source

The jQuery $ sign is in the global area. Everything can refer to it. You reach the value of the form flag in $.

0
source

Source: https://habr.com/ru/post/1343692/


All Articles