Friday, May 3, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  198] [ 1]  / answers: 1 / hits: 46170  / 13 Years ago, mon, may 16, 2011, 12:00:00

i want to pass a function to another function as a parameter.



I want to do that because the latter function calls an async Jquery method and AFTER that gives a result back, i want some javascript code executed.



And because this function is called from multiple places, i want the code to execute (after the async Jquery code gets executed) to be passed in the function.
Makes sense? i hope :)



Now what is see is that the order in which the code is executed is noth what i want.
I've simplified the code to this code:



$('#AddThirdParty').click(function() {
var func = new function() {
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute;
}


Now what i wanted to achieve (or at least what i thought would happen) was that alert4 would fire, then the loadhtml would fire alert1, alert2 and alert3, and then the code would return to alert5.



But what happens is this: alert1, alert2, alert3, alert4, alert5.



Does anyone know what i'm doing wrong and why this is the order in which the code is executed?



It looks like the alert1..alert3 gets executed when i define the new function(), but why doesn't it ALSO get executed when i call it from the LoadHtml function?


More From » jquery

 Answers
8
$('#AddThirdParty').click(function() {
var func = function() { // NOTE: no new
alert('1');
alert('2');
alert('3');
}
alert('4');
LoadHtml(func);
alert('5');
});
function LoadHtml(funcToExecute) {
//load some async content
funcToExecute(); // NOTE: parentheses
}


Two errors: the syntax for anonymous functions does not include the keyword new; and JavaScript requires parentheses for function calls, even if functions do not take any arguments. When you just say funcToExecute, that is just a variable giving its value in a context where nothing is using that value (kind of like writing 3; as a statement).



You might notice that you already know how to use anonymous functions: you did not write $('#AddThirdParty').click(new function() ...);


[#92224] Friday, May 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiem

Total Points: 456
Total Questions: 116
Total Answers: 101

Location: Dominica
Member since Mon, Jan 4, 2021
3 Years ago
;