I have a problem with my code bellow:
for (var i =0; i < filterArray.length; i++)
{
name1 = filterArray[i];
selectstring = 'a[cat="'+name1+'"]';
filterMenuItem.addItem(name1 , function() {$(selectstring).show(); alert(selectstring)});
}
filterArray contains 2 items currently.. “Foo” & “Bar”..
now this “addItem(name1” works fine. We get an added menu item with the name Foo and another named Bar
the issue comes with the next part (the function).
both the Foo & Bar menu items functions end up doing the same thing. (e.g. they both get the select string ‘a[cat=”bar”]’… as tested with the alert)
Now i assume this is happening because the selectstring variable is being passed by reference to the function? So when i’m setting selectstring value a second time it is overriding the value from the first loop?
How can I pass a unique copy of selectstring to a selector? i tried “function(selectstring) {….}” but this didn’t help..
Thanks for anyone who can shed some light on the subject!
EDIT: Revised code below.. Still same issue:
for (var i =0; i < filterArray.length; i++)
{
var name1 = filterArray[i];
var selectstring = 'a[cat="'+name1+'"]';
filterMenuItem.addItem(name1 , function() {alert(selectstring); $('.sortablelist').hide(); $(selectstring).show();});
}
It has nothing to do with “passing by reference” to the function — nothing is passed to the function, actually.
I think the problem is the variable scope.
You didn’t useThe anonymous function will keep a reference to this global variable, which will have the value of ‘bar’ by the time the function is run.varbeforeselectstringon the assignment line, so it’s assumed to be a global variable.If you usevar selectstring = (...), a separate closure will be created on each iteration, and it should work.EDIT
I answered too fast, and the answer was wrong, so here is an updated solution. I assumed a closure was being created when the anonymous function was declared, but that’s not the case. So the actual solution involves creating a closure to retain the variable’s value for each loop iteration:
Working example on jsfiddle
The solution I posted as a comment below also works, and is based on the same principle, but I think it looks bad for involving an unnecessary self-executing function.
See also this SO thread discussing the same subject.