Elaine
Elaine

Reputation: 1318

Can a callback have parameters defined?

I know it's maybe an fairly easy basic knowledge for you, here I need to ask your help to see whether there is a 'hole' behind to improve. Please check the code below, can I set 'response' as callback parameter but not callSvc's? instead of this kinda 'tricky' way?

function callSvc(response, callback){
    callback(response);
}

callSvc("I'm a response!",function(param_response){document.write(param_response);});

Thanks..

Update

Maybe this is good enough?

function callSvc(callback) {
    callback("response");
}
callSvc(function(data) {
    document.write(arguments[0]);
});

Upvotes: 0

Views: 125

Answers (3)

Marcus Whybrow
Marcus Whybrow

Reputation: 19998

Instead of defining your callback anonymously define it before hand:

function callSvc(response, callback){
    callback(response);
}

function cb(param_response) {
    document.write(param_response);
}

Then you can use it in a call to callSvc or on its own:

callSvc("I'm a response!", cb);

cb("I'm a response!");

Upvotes: 1

Pierreten
Pierreten

Reputation: 10147

There shouldn't be anything tricky about closures in javascript. They are a language feature.

You can avoid the wrapping callSvc function as well, and jump straight into this:

var response = "I'm a response"

var callback = function(){document.write(response);};

The callback function can "see" response as if you passed it as a parameter, since it forms a closure.

callback();  //I'm a response

Upvotes: 1

mpen
mpen

Reputation: 282845

Eh? All that code looks to be the equivalent of

document.write("I'm a response!");

So you can bypass all the methods. You can also declare an anonymous function and call it immediately, if that's what you wanted to do:

(function(param_response){document.write(param_response);})("I'm a response!");

Or lastly, if you need to pass parameters to a callback that doesn't except any, then wrap it in an anonymous funciton

func_that_takes_callback(function(){the_real_callback(arg);});

Upvotes: 1

Related Questions