I have the following code:
for (_field in _fields) {
$.post(
'/api/fields',
{ id: _field.id },
function(data, _field) {
alert(data);
} (data, _fields[_field)
);
}
I have to pass the _fields[_field] element to the function that returns the data from the jQuery because loses the reference to the right object during the loop. The problem is that in defining that the post function should have a _field parameter, you also have to specify a parameter for data, or data will be overwritten with _field.
Currently data returns as undefined because I have no data object defined inside the loop. I also tried passing in null, but that also just returns null. I’m looking for a way to pass the element without overwriting the data returned from the post function.
Is there any way to fix this, or is there perhaps an alternative jQuery method that can do what’s needed?
You want a function factory function — a function that creates a function:
Note that in the object initializer we’re passing into
$.post, we’re callingmakeHandlerto it runs and returns the function we’ll then pass into$.post. That function is then called when the$.postcompletes, and has access to thedataargument that$.postgives it as well as thefieldargument tomakeHandler, because it’s a closure over the context of the call tomakeHandler, which includes thefieldargument. More: Closures are not complicatedNote that in the code above, I changed your variable
_fieldto_fieldNameto be more clear: The variable infor..inloops is a string, the name of a property. See also the comment, I think you were trying to use.idin the wrong place. Here’s what I think you really wanted:Also note that if
_fieldsis an array, you shouldn’t usefor..inon it without safeguards. More: Myths and realities offor..in