Skip to content
June 11, 2011 / pauldundon

Creating Curried Javascript Functions in a Loop

The problem: You want to create a series of curried functions (for example, as event handlers for an array of elements) and attempt to do so using a loop, as follows:

function foo() {
	for (i = 0; i < elements.length; ++i) {
		var element = elements[i];
		var otherData = someArray[i]
		$addHandler(item, "click", function () { doSomething(otherData); });
	}
}

However, clicking on the items (in this example) produces the same result for every item, specifically, each item is associated with the last value in otherData referenced by the loop.

The cause: Javascript is evaluating otherData at the point of invocation rather than at the point of constructing the anonymous function (as VB would). As a consequence, it always takes its most recent value.

The solution: Create your curried function within another function. This creates an independent scope for each instance of the currying parameters:

function foo() {
	for (i = 0; i < elements.length; ++i) {
		var element = elements[i];
		var otherData = someArray[i]
		$addHandler(item, "click", createHandler(otherData));
	}
}

function createHandler(param) {
	return function () { doSomething(param); }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: