Anders
Anders

Reputation: 6218

Event Listener and AJAX asynchronous function variable scope

I got a question, probably very simple, but whatever. When registering an event listener inside an asynchronous function, I would believe that all values within that function would be non-existing when the function has run it's course.

However, an event listener, as displayed below in the code can still access the variable values, how is that? Is the variable saved within 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);
        });
    }
});

Upvotes: 4

Views: 1493

Answers (2)

Wayne
Wayne

Reputation: 60414

This is because of closures. A function "closes over" all variables in its lexical scope, which is to say that it retains access to them once the function in which it was defined has returned.

In your specific example, values is in scope when the function given to click is defined, so it will remain accessible even once success completes.

You'll find a lot more information here:

Upvotes: 2

Adolph Trudeau
Adolph Trudeau

Reputation: 361

The JQuery $ sign is in the global scope. Anything can reference it. You are reaching the form checkbox values through $.

Upvotes: 0

Related Questions