View Single Post
  #2 (permalink)  
Old Jul 22nd, 2006, 11:15
spinal007's Avatar
spinal007 spinal007 is offline
Moderator
Join Date: Mar 2004
Location: Good Ol'London
Age: 23
Posts: 1,650
Blog Entries: 1
Thanks: 0
Thanked 4 Times in 4 Posts
Re: Pre-defining a function that can pass variables.

Ok, we need to get this string:
... = Function('callWhenDone(passThisVar)');
do you mean...
... = function(){ callWhenDone(passThisVar); };
Were you just giving passing the idea or actually showing code???


***
You'll need to clarify that before I can help you. I don't know exactly what the situtation is but this might help... (based on what you've given me)

For a string, you could do this:
var testFunction = Function('callMe("'+varToPass+'");');

For a number, you could do this:
var testFunction = Function('callMe('+varToPass+');');

For a dom element, try passing the element id as a string.

***
Another approach would be to, instead of sending the variable as a parameter, send a function as a parameter which would get the current value of the variable you're trying to pass. eg:
... = Function('callWhenDone(LoadTheVarToPass())');

***
I know what the problem with the above is: the variable varToPass will have been updated by the time the function is called. Well, how you solve this will depend on your code's structure / variable scope.

If varToPass is a global variable, then this should work. As far as I now, it's the proper way to do it and it would always execute using the current value of varToPass.

// define function
obj.testFunction = new function(){ callMe(varToPass); };
// call function
obj.testFunction();


***
hope that helps...

Last edited by spinal007; Jul 22nd, 2006 at 11:19.
Reply With Quote