How to pass argument to a method called in setTimeout or on a event binding
By Vincent DEMAY, Thursday 2 August 2007 :: IE sucks :: #68 :: rss
Imagine you want (with javascript of course) giving an argument to a timeout method(it is the same for event connector)
ie
This will not work because the function executed on timeOut can not have access to
first : You can use an eval BUT this will throw some exception in our dear IE :
ie
function aFunction(aVariable){
window.setTimeout(myFunction(){alert(aVariable)}, 500);
}
This will not work because the function executed on timeOut can not have access to
aVariable. So there are to way to deal with thatfirst : You can use an eval BUT this will throw some exception in our dear IE :
function aFunction(aVariable){
window.setTimeout(eval("myFunction(){alert('" + aVariable + "')}", 500);
}
Second, the better You can use a function returning a function :
function aFunction(aVariable){
window.setTimeout(getOnTimeOut(aVariable), 500);
}
function getOnTimeOut(aVariable){
return function(){ // no params
alert(aVariable);
}
}
Power by
Comments
1. Le Friday 3 August 2007 , par Sylvain Wallez
2. Le Saturday 26 April 2008 , par MaD HamsteR
3. Le Saturday 10 May 2008 , par Bob
4. Le Wednesday 7 October 2009 , par KaZ
Add a comment