Reputation: 7048
function firstCallme(iWantToBePassed) {
post(callbackFun);
}
// This function shouldn't be anonymous.
function callbackFun(dataFromPostFun) {
alert(iWantToBePassed);
}
How to pass the variable iWantToBePassed from firstCallme() to callbackFun()? There are several similiar question in SO. But I couldn't identify the solution from it.
I know only one solution as given below:
function firstCallme(iWantToBePassed) {
post(function(data){callbackFun(data,iWantToBePassed) });
}
// This function shouldn't be anonymous.
function callbackFun(dataFromPostFun, iWantToBePassed) {
alert(iWantToBePassed);
}
Is there any better solution?
UPDATE:
here:
function post(callbackFun) {
jQuery.post('url', 'data', callbackFun, 'json');
}
Upvotes: 2
Views: 519
Reputation: 844
Just call the callbackFun function with the parameter to should be passed.
The parameter after the function is what is posted, you don't have to tell the JavaScript browser to post something, it already knows it has to post (pass) a variable to a function when it is declared between the parentheses.
function firstCallme(iWantToBePassed) {
callbackFun(iWantToBePassed);
}
function callbackFun(dataFromPostFun) {
alert(dataFromPostFun);
}
*edit:
The jQuery.post function is an asynchronous javascript call (to get data without a page load).
So when used jQuery.post you can pass parameters to a php script for example and get an answer from it. A short-hand function for this is $.ajax() for example.
With jQuery.post you send 'data' to an 'url' and the 'callbackFunction' is the function that handles the answer. the 'json' in your question is the data type.
In your case this would become something like this:
function firstCallme(postData){
jQuery.post("url.php", postData, callbackFun(data), "json");
}
callbackFun(successData){
console.log(successData);
}
Upvotes: 1
Reputation: 3276
Since your callback function is invoked after a post
then the only way to pass parameters to the callback function is to use some form of Closure like you showed in the solution you mentioned in your question.
You can also post your parameter iWantToBePassed
and retrieve it from the data in the post in your callback function. But I wouldn't recommend this route unless you need that parameter on the server.
Upvotes: 2
Reputation: 74738
Try it this way: http://jsfiddle.net/6WxfF/
function firstCallme(iWantToBePassed) {
callbackFun(iWantToBePassed);
}
function callbackFun(dataFromPostFun) {
post(dataFromPostFun);
}
function post(callbackFun) {
jQuery.post('url', 'data', callbackFun, 'json');
}
$(function() {
var hel = "Hello";
firstCallme(hel);
});
Upvotes: 0
Reputation: 66663
Rewrite post
as:
function post(callbackFun, param) {
jQuery.post('url', 'data', function() { callbackFun(param); }, 'json');
}
And call it like:
function firstCallme(iWantToBePassed) {
post(callbackFun, iWantToBePassed);
}
Upvotes: 0