Posts Tagged ‘closure’

Keep Original Variable State Between Event Binding and Execution

Wednesday, July 15th, 2009

Or: Binding Events Inside of a Loop with jQuery

I wrote an article over on the LANIT Development Blog about saving the state of a variable inside a closure that is not executed immediately. For example, functions passed into event binding or setTimeout(). Here is a quick rundown of the problem and the solution (using the jQuery library).

The Problem

$(function() {
	$("body").append("<ul id='container'></ul>");
 
	for (var i = 0; i < 5; i++)
	{
		var $item = $("<li />").text("Item " + i);
		$("#container").append($item);
 
		$item.click(function() {
			alert("You clicked number " + i);  // always "You clicked number 5"
		});
	}
});

The Solution

$(function() {
	$("body").append("<ul id='container'></ul>");
 
	for (var i = 0; i < 5; i++)
	{
		var $item = $("<li />").text("Item " + i);
		$("#container").append($item);
 
		(function() { // Closure here here instead of "bindItem()"
			var ind = i;
			$item.click(function() {
				alert("You clicked number " + ind); // Works as expected
			});
		})(); // Execute immediately
	}
});

The solution uses an immediately executing function to create a new scope and declare a variable “ind” that is reserved a new space in memory instead of simply referencing “i”. Check out the full article for more details.