As soon as you stick parentheses on, it stops being a callback. scene.myCallBack
can act as a callback; scene.myCallBack("mymap")
is just undefined
(the return value of your function, as it does not have an explicit return
statement and thus implicitly returns undefined
).
If you want to have he $.ajax
do myCallBack
on success AND have custom arguments with it, you need to wrap it:
scene.foo(function() { scene.myCallBack("mymap"); });
Or equivalently,
fooCallback = function() { scene.myCallBack("mymap"; };
scene.foo(fooCallback);
EDIT to clarify some concepts:
And can you explain why putting parentheses on it makes it not a callback?
Putting parentheses on a function executes a function, giving a value back. A callback must be a function.
For example, let's say your Mum wants you to eat an apple when you get home. She could leave you a note, "Growler, when you get home, eat an apple!":
var eatApple = function() {
growler.eat('apple');
}
growler.on('getHome', eatApple);
is one way to write such a thing. However, if you write
growler.on('getHome', eatApple());
it's like your Mum feeding you an apple, then writing a note "Growler, when you get home, __" and placing the apple core on the blank. I don't know about you, but I'd be rather surprised by such a note; and I daresay your JavaScript interpreter is likewise surprised as well.
A callback is a function to be done at a later time. If you execute it (with parentheses), you are only left with the function's results; and thus the function is not a callback, since your event will try to call back the result (the apple core), and not the function (process of eating an apple).
(An advanced topic is a function that returns a function; in this case, the result can be the callback, such as, growler.on('getHome', whatShouldIDoNow())
. whatShouldIDoNow
is still not a callback; the function that it would return would be.)
If $.getJSON is already an AJAX request, how can I get the callback from that?
I do not understand the question. You provide $.getJSON
with callbacks at the time you invoke it; those functions will be called back at the appropriate time, if such happens.