Eoghan
2008-12-03 15:18:50 UTC
I commonly use forEach within another function, like the following
example:
connect(el, 'onclick', function(e){
var my_var = getNodeAttribute(e.src(), 'someattr');
forEach(getElementsByTagAndClassName('div', 'some_class'),
function(mydiv){
if(getNodeAttribute(mydiv, 'someattr') == my_var){
// do something
}
}
});
Unfortunately 'my_var' takes on unexpected values, because the
function that acts as the body of the forEach is a closure (I think).
Converting the above code to use a plain old 'for' loop acts as
expected:
connect(el, 'onclick', function(e){
var my_var = getNodeAttribute(e.src(), 'someattr');
var arr = getElementsByTagAndClassName('div', 'some_class');
for(var i=0; i<arr.length; i++){
var mydiv = arr[i];
if(getNodeAttribute(mydiv, 'someattr') == my_var){
// do something
}
}
});
Using a partial function for the forEach body with 'my_var'
preinitialised seems clunky to me and definitely reduces readability.
What is the most elegant way to make forEach behave as expected (as
illustrated by the second example)?
Thanks!
Eoghan
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "MochiKit" group.
To post to this group, send email to ***@googlegroups.com
To unsubscribe from this group, send email to mochikit+***@googlegroups.com
For more options, visit this group at http://groups.google.com/group/mochikit?hl=en
-~----------~----~----~----~------~----~------~--~---
example:
connect(el, 'onclick', function(e){
var my_var = getNodeAttribute(e.src(), 'someattr');
forEach(getElementsByTagAndClassName('div', 'some_class'),
function(mydiv){
if(getNodeAttribute(mydiv, 'someattr') == my_var){
// do something
}
}
});
Unfortunately 'my_var' takes on unexpected values, because the
function that acts as the body of the forEach is a closure (I think).
Converting the above code to use a plain old 'for' loop acts as
expected:
connect(el, 'onclick', function(e){
var my_var = getNodeAttribute(e.src(), 'someattr');
var arr = getElementsByTagAndClassName('div', 'some_class');
for(var i=0; i<arr.length; i++){
var mydiv = arr[i];
if(getNodeAttribute(mydiv, 'someattr') == my_var){
// do something
}
}
});
Using a partial function for the forEach body with 'my_var'
preinitialised seems clunky to me and definitely reduces readability.
What is the most elegant way to make forEach behave as expected (as
illustrated by the second example)?
Thanks!
Eoghan
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "MochiKit" group.
To post to this group, send email to ***@googlegroups.com
To unsubscribe from this group, send email to mochikit+***@googlegroups.com
For more options, visit this group at http://groups.google.com/group/mochikit?hl=en
-~----------~----~----~----~------~----~------~--~---