4

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);
        });
    }
});
Anders
  • 6,188
  • 4
  • 26
  • 31
  • The JavaScript Garden doesn't give an explicit answer, but does use it as a solution to `this` references: http://bonsaiden.github.com/JavaScript-Garden/#function.this (Common Pitfalls, 2nd snippet). – pimvdb Mar 14 '11 at 21:36

2 Answers2

2

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:

Community
  • 1
  • 1
Wayne
  • 59,728
  • 15
  • 131
  • 126
  • @Anders - It's accessible to any function defined in `success`. In your example, the function given to `click` is the only function that's still "alive" after the call to `success` so it's the only function that retains access. However, imagine you were to define another function inside `success` and then `return` it from `success`. You'd be able to call that function later and it would have access to `values`. – Wayne Mar 14 '11 at 21:51
0

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

Adolph Trudeau
  • 351
  • 1
  • 8
  • 1
    @user344215 - That's not what he asked. He's wondering why the inner function can still access `values` once `success` has returned. – Wayne Mar 14 '11 at 21:40
  • Oh, I thought he was referring to the form values, not the local scope "values" in success. I understand the question now as "How can the anonymous function bound to the click event of $("#id :checkbox") access the array named values created in my $.ajax success event?" – Adolph Trudeau Mar 14 '11 at 21:53