473,216 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,216 software developers and data experts.

passing a function name to another funtion

I have a system that I want to try, which requires me, from an aspx
page, to call a generic function to work perform one task, then i want
to call another function with the results of that task.

something like this:

in my aspx page:
<input type=button onClick="doFirstFunction('secondFunctionName');">

then in my .js file:

var functionToCall = '';

function doFirstFunction(functionName) {

functionToCall = functionName

// do the initial, common task
sResult = xmlHttp.responseText

//now call the second function, passing sResult to it

}

Right now I'm using 'switch' and manually adding possible values for
'functionName' then directing manually, but I'd like to make
"doFirstFunction" self-maintaining, i.e. without having to update it if
I add more 'second' functions later.

I thought I could use

eval('functionToCall('+sResult+')');

but this doesn't work so far.

any ideas?

Apr 21 '06 #1
17 8528
VK

Kevin Blount wrote:
I have a system that I want to try, which requires me, from an aspx
page, to call a generic function to work perform one task, then i want
to call another function with the results of that task.

something like this:

in my aspx page:
<input type=button onClick="doFirstFunction('secondFunctionName');">


Remove apos' and it will become ready to use function reference
(presuming that the secondFunctionName exists at the moment of click:
<input type="button" onclick="firstFunction(secondFunction);">
....
function firstFunction(ptr) {
// do stuff
ptr();
}

Alternatively (if you prefer handle strings) all existing functions are
tunelled through the window object, so:

<input type="button" onclick="firstFunction('secondFunction');">
....
function firstFunction(str) {
// do stuff
window[str]();
}

Apr 21 '06 #2
VK said the following on 4/21/2006 4:22 PM:
Kevin Blount wrote:
I have a system that I want to try, which requires me, from an aspx
page, to call a generic function to work perform one task, then i want
to call another function with the results of that task.

something like this:

in my aspx page:
<input type=button onClick="doFirstFunction('secondFunctionName');">
Remove apos' and it will become ready to use function reference
(presuming that the secondFunctionName exists at the moment of click:
<input type="button" onclick="firstFunction(secondFunction);">
....
function firstFunction(ptr) {
// do stuff
ptr();
}


ptr is undefined unless that is the name of the function.
Alternatively (if you prefer handle strings) all existing functions are
tunelled through the window object, so:

<input type="button" onclick="firstFunction('secondFunction');">
....
function firstFunction(str) {
// do stuff
window[str]();
}


That is the only way to do it that you have mentioned. And the apos'
have to be on the initial function call.
--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Apr 21 '06 #3
VK

Randy Webb wrote:
function firstFunction(ptr) {
// do stuff
ptr();
}


ptr is undefined unless that is the name of the function.


Are you positive about it? ;-)

<html>
<head>
<title>F2F</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function f1(ptr) {
alert('f1');
ptr();
}
function f2() {
alert('f2');
}
</script>
</head>

<body>
<p style="cursor:pointer; color:#0000FF; text-decoration:underline"
onClick="f1(f2);">Click me</p>
</body>
</html>

Apr 21 '06 #4
Randy Webb wrote:
<input type="button" onclick="firstFunction('secondFunction');">
....
function firstFunction(str) {
// do stuff
window[str](); <===================
}

That is the only way to do it that you have mentioned. And the apos'
have to be on the initial function call.


Could you please explain how this works? It seems like the answer to my
query (indirect function calls) but I don't see how that works.

Are entities (objects, whatever you call them) all elements in a window
array? (Sorry if this is newb Q; I am fairly new to javascript...)

--Yan
Apr 21 '06 #5
VK

Captain Dondo wrote:
Are entities (objects, whatever you call them) all elements in a window
array? (Sorry if this is newb Q; I am fairly new to javascript...)


They are "accessible as named properties of the window object" (I hope
that this diplomatic answer covers both IE and non IE situations wich
are rather different).
At the same time they are not enumerable.

The above means that having a conventional HTML page and function
called myFunction, you can call it in the conventional way:
myFunction();
and in the alternate way:
window["myFunction"]();

Apr 21 '06 #6
VK wrote:
Alternatively (if you prefer handle strings) all existing functions are
tunelled through the window object, so:

<input type="button" onclick="firstFunction('secondFunction');">
...
function firstFunction(str) {
// do stuff
window[str]();
}


Better:

// in global context
var _global = this;

function firstFunction(str)
{
// do stuff
_global[str]();
}

Both approaches require that secondFunction() is declared in global context,
of course.
PointedEars
Apr 21 '06 #7
VK wrote:
Captain Dondo wrote:
Are entities (objects, whatever you call them) all elements in a window
array? (Sorry if this is newb Q; I am fairly new to javascript...)

They are "accessible as named properties of the window object" (I hope
that this diplomatic answer covers both IE and non IE situations wich
are rather different).
At the same time they are not enumerable.

The above means that having a conventional HTML page and function
called myFunction, you can call it in the conventional way:
myFunction();
and in the alternate way:
window["myFunction"]();


OK< that sounds like what I need.... How do I test for existence of
such an entity?

if(window["myFunction']) window["myFunction"](a,b,c);

??
Apr 21 '06 #8
VK wrote:
Captain Dondo wrote:
Are entities (objects, whatever you call them) all elements in a window
array? (Sorry if this is newb Q; I am fairly new to javascript...)
They are "accessible as named properties of the window object" (I hope
that this diplomatic answer covers both IE and non IE situations wich
are rather different).


It covers /only/ the _HTML environment_ in _known_ _graphical_
_Web browsers_, which is its major flaw.
At the same time they are not enumerable.
In the IE AOM.
The above means that having a conventional HTML page and function
called myFunction, you can call it in the conventional way:
myFunction();
and in the alternate way:
window["myFunction"]();


See news:35****************@PointedEars.de
PointedEars
Apr 21 '06 #9
VK

Thomas 'PointedEars' Lahn wrote:
VK wrote:
They are "accessible as named properties of the window object" (I hope
that this diplomatic answer covers both IE and non IE situations wich
are rather different).


It covers /only/ the _HTML environment_ in _known_ _graphical_
_Web browsers_, which is its major flaw.


The statement "window host object and Global object are the same"
covers only non-IE based browsers. The statement "Global object
tunells/peers its members through the window host object" covers
IE-based browsers. Both segments are too big to neglect, so an
"abstracted" yet correct explanation is better IMHO if it's not the
main question of the topic.

<offtopic>
Concerning some beloved spooky cases "Global object is here, but window
host is not": no one of them unfortunately is qualified to be taken
seriously.
Adobe SVG Viewer or Corel SVG Viewer are ancient and proprietary
plugins which are not more of anyone's concerns than say some
FoobarPlugin 0.01 behavior. Whatever happens where - it happens, and
thanks God if you come out alive :-)

And missing window host in a XSLT transformed page or a SVG page is not
a feature of the relevant formats, but a strong sign of a clueless
design. It just shows that the author still did not get that in XML the
used *parts* are not anyhow equal to the *resulted document*. In the
particular she may missed to tell in .xsl layout something like:
<xsl:output
method='html'
media-type='text/html'
version='4.01'
doctype-public='-//W3C//DTD HTML 4.01 Strict//EN'
doctype-system='http://www.w3.org/TR/html401/strict.dtd'
encoding='ISO-8859-1'
indent='no'/>
And again in this case no one is more responsible for the script
behavior than say in case of not closed properly <script> tag.

</offtopic>
At the same time they are not enumerable.


In the IE AOM.


As a reflection of Global/window differences in IE I started this post
with.

Apr 21 '06 #10
VK wrote:
Thomas 'PointedEars' Lahn wrote:
VK wrote:
> They are "accessible as named properties of the window object" (I hope
> that this diplomatic answer covers both IE and non IE situations wich
> are rather different).


It covers /only/ the _HTML environment_ in _known_ _graphical_
_Web browsers_, which is its major flaw.


The statement "window host object and Global object are the same"
covers only non-IE based browsers.


It covers exactly _no_ browser.
PointedEars
Apr 21 '06 #11
VK

Captain Dondo wrote:
How do I test for existence of
such an entity?

if(window["myFunction']) window["myFunction"](a,b,c);


Within the conditional checks JavaScript resolves empty strings, 0,
null, undefined and NaN to false.

Non-empty strings, non-zero numbers and references of any kind are
resolved to true.

If property doesn't exist, you'll get undefined which is covered by the
list above. So the frequently used way is:

// undefined gets resolved to boolean false:
if (window["myFunction"]) { window["myFunction"](); }
else { alert("Function doesn't exists"; }

Apr 21 '06 #12
VK wrote:
Captain Dondo wrote:
How do I test for existence of such an entity?

if(window["myFunction']) window["myFunction"](a,b,c);
Within the conditional checks JavaScript resolves empty strings, 0,
null, undefined and NaN to false.


Evaluated, not resolved. And that goes for all ECMAScript implementations.
Non-empty strings, non-zero numbers and references of any kind are
resolved to true.
Evaluated, not resolved.
If property doesn't exist, you'll get undefined which is covered by the
list above. So the frequently used way is:
Probably used by /you/. Along with your other numerous failed attempts at
proper programming.
// undefined gets resolved to boolean false:
if (window["myFunction"]) { window["myFunction"](); }
else { alert("Function doesn't exists"; }


However, much better is:

// in global context
var _global = this;

// anywhere "after" the above
if (typeof _global["myFunction"] == "function")
{
_global["myFunction"]();
}
else
{
window.alert("Function does not exist");
}

Under the provision that `myFunction' is declared globally.

And the bracket property accessor is not necessary at all
if you already know the identifier: _global.myFunction

If all the code is in global context, one can use `this'
explicitly and does not have to declare the `_global'
variable. And `typeof myFunction' would suffice then.
PointedEars
Apr 21 '06 #13
Randy Webb <Hi************@aol.com> writes:
VK said the following on 4/21/2006 4:22 PM:
<input type="button" onclick="firstFunction(secondFunction);">
....
function firstFunction(ptr) {
// do stuff
ptr();
}


ptr is undefined unless that is the name of the function.


ptr is a parameter (and therefore a local variable) of firstFunction.
It is declared in the context where it is used, and will have a value
if one is passed to firstFunction, as it appears from the usage
that one is.
It's not undefined, and it's independent of the name of the function
being passed.

This is the best way to pass functions to other functions: as values.
Passing their names and requireing an explicit lookup is much more
fragile, less readable, requires the passed function to be globally
availalbe, and is all together unnecessary if you have the function
available where you call the first function.
<input type="button" onclick="firstFunction('secondFunction');">

That is the only way to do it that you have mentioned. And the apos'
have to be on the initial function call.


That's the only way to pass a function's name, which was what to OP
asked for.
It's definitly not the only way to have one function call a second,
where which second function is called is controlled by a parameter of
the first, which perhaps was what to OP really wanted.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Apr 22 '06 #14
I finally got back around to this, and found that this solution worked
perfectly. Manty thanks VK

VK wrote:
Alternatively (if you prefer handle strings) all existing functions are
tunelled through the window object, so:

<input type="button" onclick="firstFunction('secondFunction');">
...
function firstFunction(str) {
// do stuff
window[str]();
}


May 8 '06 #15
Kevin Blount wrote:
I finally got back around to this, and found that this solution worked
perfectly. Manty thanks VK
Please don't top-post.

VK wrote:
Alternatively (if you prefer handle strings) all existing functions are
tunelled through the window object, so:


No, they aren't[1].

Functions may be accessed through a property of the global object where
they are declared in a global scope or the value of a global property is
assigned a reference to a function (e.g. using function expression).

In browsers, the window object is equivalent to the global object, but
not all user agents are browsers and not all have a window object.
1. What does 'tunelled' mean in a JavaScript context? The correct
spelling is 'tunneled', and when used in an IT or computing context
refers to the encapsulation of one network protocol inside another. It
is normally used to transport a network protocol across a network that
otherwise wouldn't support it. I don't see how that applies to
JavaScript at all.
--
Rob
Group FAQ: <URL:http://www.jibbering.com/faq/>
May 10 '06 #16
RobG wrote:
[...]

1. What does 'tunelled' mean in a JavaScript context? The correct
spelling is 'tunneled'


'Tunneled' is the US spelling, 'tunnelled' is the English spelling
(Oxford dictionary).
--
Rob
Group FAQ: <URL:http://www.jibbering.com/faq/>
May 10 '06 #17
Please don't top post? whatever man..

May 10 '06 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: domeceo | last post by:
can anyone tell me why I cannot pass values in a setTimeout function whenever I use this function it says "menu is undefined" after th alert. function imgOff(menu, num) { if (document.images) {...
58
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of...
0
by: Zlatko Matić | last post by:
Hi everybody! Recently I was struggling with client/server issues in MS Access/PostgreSQL combination. Although Access is intuitive and easy to use desktop database solution, many problems...
4
by: Pushkar Pradhan | last post by:
I want a function to execute another function, which I pass to it, sometimes it may be mm_6r6c_6r6c, mm_2r2c_2r2c, ... etc. thus this style. double exec_basecase(void (*func)(double *a, double...
2
by: nagle.p | last post by:
Ok, Im writting a plug-in for a application and the class the I have to derive from has a warp() funtion that gets called that is part of the base class. I need to pass a varible into this...
5
by: Lee Xuzhang | last post by:
/* from SICP -- Exercise 4.21: ((lambda (n) ((lambda (fact) (fact fact n)) (lambda (ft k) (if (= k 1) 1 (* k (ft ft (- k 1))))))) 10) */
5
by: steven_orocos | last post by:
Hi, I'm tryin to pass a funtion as an argument in another funtion. This code works ---------------------------------- typedef void (*func)(int); void test1(int a){cout<<"1";} void...
13
by: masso600 | last post by:
char word; in = fopen("test.txt", "r"); while(fscanf(in,"%s",&word)!=EOF) { /* Print all words */ /* printf("%s\n",&word); */
1
by: shalabh6 | last post by:
Hi, A js file containing a function which is passing an alphanumeric string to another function in the same file, the second funtion requires 4 parameters to pass from the first function. The...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.