Closures in jQuery
The methods we have seen throughout the jQuery library often take at least one function as a parameter. For convenience, we often use anonymous functions , so that we can define the function behavior right when it is needed. This means that functions are rarely in the top-level namespace; they are usually inner functions, which means they can quite easily create closures.
Arguments to $(document).ready()
Nearly all of the code we write using jQuery ends up getting placed inside a function passed as an argument to $(document).ready()
. We do this to guarantee that the DOM has loaded before the code is run, which is usually a requirement for interesting jQuery code. When a function is created and passed to .ready()
, a reference to the function is stored as part of the global jQuery
object. This reference is then called at a later time, when the DOM is ready.
We usually place the $(document).ready()
construct at the top level of the code structure, so this function is not really part of a closure. However, as our code is usually written inside this function, everything else is an inner function:
$(document).ready(function() { var readyVar = 0; function innerFn() { readyVar++; $.print('readyVar = ' + readyVar); } innerFn(); innerFn(); });
This looks like many of our earlier examples, except that in this case, the outer function is the callback passed to $(document).ready()
. As innerFn()
is defined inside of it, and refers to readyVar
which is in the scope of the callback function, innerFn()
and its environment create a closure. We can see this by noting that the value of readyVar
persists between calls to the function.
readyVar = 1 readyVar = 2
The fact that most jQuery code is inside a function body is useful, because this can protect against some namespace collisions
. For example, it is this feature that allows us to use jQuery.noConflict()
to free up the $
shortcut for other libraries, while still being able to define the shortcut locally for use
within $(document).ready()
.
Event handlers
The $(document).ready()
construct usually wraps the rest of our code, including the assignment of event handlers. As handlers are functions, they become inner functions. As those inner functions are stored and called later, they can create closures. A simple click
handler can illustrate this:
$(document).ready(function() { var counter = 0; $('#button-1').click(function() { counter++; $.print('counter = ' + counter); return false; }); });
As the variable counter
is declared inside of the .ready()
handler, it is only available to the jQuery code inside this block and not to outside code. It can be referenced by the code in the click
handler, however, which increments and display the variable's value. As a closure is created, the same instance of counter
is referenced each time the link is clicked. This means that the messages displays a continuously incrementing set of values, not just 1 each time as follows:
counter = 1 counter = 2 counter = 3
Event handlers can share their closing environments, just like other functions:
$(document).ready(function() { var counter = 0; $('#button-1').click(function() { counter++; $.print('counter = ' + counter); return false; }); $('#button-2').click(function() { counter--; $.print('counter = ' + counter); return false; }); });
As both of the functions reference the same counter variable, the incrementing and decrementing operations of the two links affect the same value rather than being independent:
counter = 1 counter = 2 counter = 1 counter = 0
Binding handlers in loops
Looping constructs can pose interesting challenges due to the way closures operate. Consider a scenario in which we create elements in a loop and bind behaviors to those elements based on the loop's index as follows:
$(document).ready(function() { for (var i = 0; i < 5; i++) { $('<div>Print ' + i + '</div>') .click(function() { $.print(i); }).insertBefore('#results'); } });
The variable i
is set to the numbers 0 through 4 in turn, and a new <div>
element is created each time. The elements each have a unique text label, as we would expect:
Print 0 Print 1 Print 2 Print 3 Print 4
However, clicking on any of these items will result in the number 5
being printed on the page and not the number matching the item label as we might expect. Each click
handler's reference to i
is the same; even though the value of i
is different at the time the handler is bound, the variable is the same one and so the final value of i
(5) is fetched when a click actually happens.
We can get around this problem in a number of ways. First, we could replace the for
loop with the jQuery $.each()
function as follows:
$(document).ready(function() { $.each([0, 1, 2, 3, 4], function(index, value) { $('<div>Print ' + value + '</div>') .click(function() { $.print(value); }).insertBefore('#results'); }); });
Function parameters are like variables defined within functions: the variable value
is actually a different variable each time through the loop. As a result of this, each click
handler is pointing to a different value
variable, and clicks on the elements print numbers corresponding to the element labels, as we planned.
We can also exploit the same properties of function parameters to solve this problem without calling $.each()
. Inside the for
loop, we can define and execute a new function that takes care of separating the values of i
apart into distinct variables as follows:
$(document).ready(function() { for (var i = 0; i < 5; i++) { (function(value) { $('<div>Print ' + value + '</div>') .click(function() { $.print(value); }).insertBefore('#results'); })(i); } });
We have seen this construct, named immediately invoked function expression (IIFE), before as a means of redefining the $
alias for the jQuery
object after $.noConflict()
has been called. Here, we use it to pass in i
as a parameter named value
that is distinct for each click
handler.
Finally, we can use a feature of the jQuery event system to solve the problem a different way. The .bind()
method accepts an object parameter that is passed along to the event handler as event.data
:
$(document).ready(function() { for (var i = 0; i < 5; i++) { $('<div>Print ' + i + '</div>') .bind('click', {value: i}, function(event) { $.print(event.data.value); }).insertBefore('#results'); } });
In this case, i
is provided as data to the .bind()
method, and can be retrieved inside the handler by inspecting event.data.value
. Once again, as event
is a function parameter, it is a unique entity each time a handler is invoked, rather than a single value being shared across them all.
Named and anonymous functions
These examples have used anonymous functions , as has been our custom in jQuery code. This makes no difference in the construction of closures; closures can come from named or anonymous functions. For example, we can write an anonymous function to report the index of an item within a jQuery object as follows:
$(document).ready(function() { $('input').each(function(index) { $(this).click(function() { $.print('index = ' + index); return false; }); }); });
As the innermost function is defined within the .each()
callback, this code actually creates as many functions as there are buttons. Each of these functions is attached as a click
handler to one of the buttons. The functions have index
in their closing environment, as it is a parameter to the .each()
callback. This behaves the same way as if the click
handler were written as a named function:
$(document).ready(function() { $('input').each(function(index) { function clickHandler() { $.print('index = ' + index); return false; } $(this).click(clickHandler); }); });
The version with the anonymous function is just a bit shorter. The position of this named function is still relevant, however:
$(document).ready(function() { function clickHandler() { $.print('index = ' + index); return false; } $('input').each(function(index) { $(this).click(clickHandler); }); });
This version will trigger a JavaScript error whenever a button is clicked, because index
is not found in the closing environment of clickHandler()
. It remains a free variable, and so is undefined in this context.