I want to attach an event coming from a string. The problem I am having is that the function names are not passing in as strings but rather being compiled when the function is called which is resulting in an undefined variable error (temp).
function someFun(arg) {
alert(arg) ;
}
temp[0] = "someFunc(test)" ;//this would be a sample of the incoming HTML
var x = 0 ;
while(temp[x] != '') {
temp[x] = temp[x].replace(')','').split('(') ;//remove paranthesis and separate func name from args
temp[x][1] = temp[x][1].split(',') ;//turn string of args into array
func = function() { window[temp[x][0]].apply(el,[]) ; }
el.addEventListener('click',func,false) ;
x++ ;
}
If I dont use temp[x][0] (which would be ‘someFunc’) but rather pass in a string for the .apply method (in this case .apply(‘someFunc’…) ) directly I have no issues and the function will be called with onClick as expected. Otherwise when I click on element el I get an error that temp is not defined.
Im pretty sure that if you assign
temp[x][0]to a variable before the functions are assigned it should work. Something like this