Reputation: 791
I'm confused about how this works. I'm not new to javascript and I have done this before, it was just a long time ago and I have since lost the code. I don't know what this scenario is referred to, as a search for the term callbacks
doesn't seem to turn up any relevant information.
1) What is this operation called? (ie: callback, passback, etc)
2) What do I do in doStuff()
to pass a parameter back to the anonymous function?
Named Function/Object below
function doStuff(param1,anonymousFunction){
//what do I do here to pass a value to 'anonymousFunction()'?
//Can I just declare a variable?
}
FunctionCall with anonymous function as parameter below
doStuff('string', function(variableThatIWantToAccess){
console.log(variableThatIWantToAccess);
});
Upvotes: 1
Views: 979
Reputation: 2645
To pass data to a callback function, simply call the callback with the correct arguments.
function doStuff( callback, data ){
callback( data );
}
doStuff( alert, 'a small dog' );
The comments show that OP was wondering about jQuery.
An example of a jQuery-event-handler-like function.
function listen( eventType, callback ){
document.addEventListener( eventType, callback );
}
Upvotes: 1
Reputation: 7336
Well, just:
function doStuff(param1, anonymousFunction) {
anonymousFunction(param1 + " parameter");
}
doStuff('string', function (variableThatIWantToAccess){
console.log(variableThatIWantToAccess); // 'string paramter'
});
AKA callback
Upvotes: 1
Reputation: 48230
function doStuff(param1,anonymousFunction){
//what do I do here to pass a value to 'anonymousFunction()'?
//Can I just declare a variable?
anonymousFunction( param1 );
}
Upvotes: 1