I am positive I asked this question in the wrong way. I am attempting to pass a string such as onClick="someFunc(arg1,arg2...)" to a javascript parser.
The parser should create an onClick event for someFunc with args (arg1, arg2 etc) .
My issue is that as the text is passed through the parser, the scope of the variable that holds the string name of someFunc is being passed down so that the attached events all register as the last declared string.
In the code below, attributes._onClick could be the string ‘onClick=”someFunc(arg1,arg2);” for one element followed by ‘onClick=”otherFunc(argA,argB);” for another element as the parser moves through the string.
The output in the browser (Firefox V14.01) has the event function always registering as otherFunc. So f_name in the closure is not evaluating as the variable but instead just registers as the last value of f_name declared throughout parsing the entire block.
I am not familiar with scope to the degree that I need to be to figure this out. Does anybody know a way I can attach the events in this manner (im trying to avoid going outside the parser to add the events) ?
temp = attributes._onClick ;
var x = 0 ;
var f_name,f_args ;
while(temp[x] != '') {
temp[x] = temp[x].replace(')','').split('(') ;//remove paranthesis and separate func name from args
f_name = temp[x][0] ;
f_args = temp[x][1].split(',') ;//turn string of args into array
el.onclick = function() { window[f_name].apply(el,f_args) ; }
x++ ;
}
You’re tripping over a pitfall in JavaScript that causes the same problem in various different ways to almost everybody at some point.
The variable “f_name” is shared among all the functions you’re creating. That is, though each iteration of the loop creates a new function, there’s only one “f_name”. Thus, all functions see the same value in it, that being the value it had on the last iteration.
There are several related solutions. One way is to wrap the statement that establishes the event handler in another anonymous function, one that you immediately invoke. That’ll allow you to create a copy of “f_name”, for exclusive use by one handler.
Interestingly, there are probably hundreds of variations on this question here on SO.