19

This question looks like a duplicate, as the title is nearly replicated. But, my issue seems simpler and I can't find the answer to it.

I have a Javascript function that executes another callback function, it works like this:

<script type='text/javascript'>
firstfunction(callbackfunction);
</script>

where callback function is defined as:

callbackfunction(response) {
    if (response=='loggedin'){
    // ... do stuff
}}

but I want it to be something like this:

callbackfunction(response, param) {
    if (response=='loggedin'){
    // ... do stuff with param
}}

My question is, does it work to pass the parameter like this:

<script type='text/javascript'>
firstfunction(callbackfunction(param));
</script>

or am I doing it wrong?

rofls
  • 4,993
  • 3
  • 27
  • 37

5 Answers5

32

In direct answer to your question, this does not work:

 firstfunction(callbackfunction(param));

That will execute callbackfunction immediately and pass the return value from executing it as the argument to firstfunction which is unlikely what you want.


It is unclear from your question whether you should just change firstfunction() to pass two parameters to callbackfunction() when it calls the callback or whether you should make an anonymous function that calls the callback function with arguments.

These two options would look like this:

function firstfunction(callback) {
    // code here
    callback(arg1, arg2);
}

firstfunction(callbackfunction);

or

function firstfunction(callback) {
    // code here
    callback();
}

firstfunction(function() {
    callbackfunction(xxx, yyy);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thanks for answering the question directly! I'm pretty sure I'll be able to get one of these methods to work. – rofls Oct 22 '12 at 02:06
11

Use an anonymous function:

function foo( callback ) {
  callback();
}

function baz( param ) {
  console.log( param );
}

foo( function(){ baz('param') });
elclanrs
  • 92,861
  • 21
  • 134
  • 171
2

Adding parameters when calling a function. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

xdaz already answered the simple version. Here is an example with variable amount of parameters.

function someObject(){
        this.callbacks=new Array();
        this.addCallback=function(cb){
            this.callbacks[this.callbacks.length]=cb
        }
        this.callCallbacks=function(){
            //var arr=arguments; this does not seem to work
            //arr[arr.length]="param2";
            var arr = new Array();
            for(i in arguments){
                arr[i]=arguments[i];
            }
            arr[arr.length]="another param";
            i=0;
            for(i in this.callbacks){
                this.callbacks[i].apply(null,arr);
                //this.callbacks[i].apply(this,arr);
                //this is a ref to currrent object
            }
        }
        this.callCallbacksSimple=function(arg){
            for(i in this.callbacks){
                this.callbacks[i](arg,"simple parameter");
            }

        }
}
function callbackFunction(){
    for(i in arguments){
        console.log("Received argument: " + arguments[i]);
    }
}
var ObjectInstance=new someObject();
ObjectInstance.addCallback(callbackFunction);
ObjectInstance.callCallbacks("call callbacks");
ObjectInstance.callCallbacksSimple("call callbacks");
HMR
  • 37,593
  • 24
  • 91
  • 160
1

function is key word, you can't use it as function name.

Let say your function name is foo, then you could do like below:

var param = 'what ever';
foo(function(response) {
  callbackfunction(response, param);
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

I think this is what you're looking for.

Lets say you're using jQuery ajax to do something, and you're passing it named callbacks. Here we have an onError callback that you might use to log or handle errors in your application. It conforms to the jQuery Ajax error callback signature, except for an extra parameter that you might have wanted to add at the back

function onError(jqXHR, textStatus, errorThrown, yourOwnVariableThing) {
    console.error('Something went wrong with ' + yourOwnVariableThing);
}

this is where your function would be called - but you want an extra parameter

$.ajax("/api/getSomeData/")
 .done(onDone)
 .fail(onError) 
 .always(onComplete);

So this is what you can do to add the extra parameter

$.ajax("/api/getSomeData/")
  .done(onDone)
  .fail(onError.bind(this, arguments[0], arguments[1], arguments[2], 'Moo Moo'); 
  .always(onComplete);

arguments is an array in JavaScript that contains all arguments passed to a function, and so you're just passing those arguments along to the callback.

Arguments

Bind

Krummelz
  • 1,046
  • 1
  • 11
  • 23