views:

283

answers:

2

How do I make the myFunction visibile for the in-line function in .ready() event?

$(document).ready(function() {
  ...stuffs...
  myFunction(par1, par2, anotherFucntion_callback);
 }
);

function anotherFunction_callback(data) {
 ..stuffs..
}
A: 

You use the actual name of the function, i.e. myFunction_callback instead of myFunction or anotherFucntion_callback.

Guffa
I wrongly typed the example. Of course myFunction_callback and anotherFunction_callback are the same.
A: 

Hi.

I didn't quite catch your question. Do you mean that you want to pass "myFunction_callback(data)" as the last argument in your:

myFunction(par1, par2, anotherFunction_callback);

, including that "data" parameter?

In that case the solution is pretty standard, write this before that one:

var temp = function() { anotherFunction_callback(data) };

an alternative syntax is:

function temp() { myFunction_callback(data) };
// even though this looks just like a free function,
// you still define it inside the ready(function())
// that's why I call it "alternative". They are equivalent.

In general, if you want to pass a function with 1 or more arguments to another function, you use that format. Here, we basically create a new no-argument function that calls another. The new function has access to the "data" variable. It's called "closure", you may want to read more on that. Of course, if the callback require no argument, you can just use the original function name.

I hope this helps.

ps: You can even inline the function declaration, making it anonymous, like so: myFunction(par1, par2, function() { myFunction_callback(data) }); Notice that the

$(document).ready(function() {});

looks pretty much just like that.

RichN
The first one you said. Thanks.