Reputation: 23901
I know that you can have functions as parameters in JS.
When I pass the statement alert("d") as a parameter -- everything fires.
dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
}, alert("d"));
But when I pass a full on function -- the statement just does not fire.
dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
}, function() {
alert("d");
});
Why might alert fire -- but the anonymous function not fire?
Upvotes: 0
Views: 46
Reputation: 37701
You're simply not calling the function in the second method. I think this, third variation might help you understand it better, along with Scott's answer:
dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
}, function() {
alert("d");
}() // <- note the () here
);
Sending just a function would be similar to just doing:
dc.embed.load('http://www.documentcloud.org/search/embed/', {some json
}, alert
);
So my first example here (sort of) matches your first example, as the functions as called, not just passed it. Also, my second example matches your second example, as we're just passing in the function body as a parameter.
To understand on the simplest example how it works, compare the values of the variables in these cases:
var a = alert;
var a = alert('hey');
And they try, for example:
a('hello there'); // for both cases
Upvotes: 0
Reputation: 6300
In the first case you are calling the function, in the second you are passing a function body but it's not being called.
Upvotes: 2
Reputation: 50787
In the first case, you are calling alert("d")
and passing the result of that, undefined
, as the third parameter to the function. So the alert runs before your load
function is even called. In the second case, the third parameter is an actual function, which, if it is ever called will perform the alert. It looks as though it is never called. You need to investigate the behavior of the dc.embed.load
function and see how and when it calls the function you pass as its third parameter.
Upvotes: 5