Javascript callback function with parameters [duplicate]

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?

Answers:

Answer

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);
});
Answer

Use an anonymous function:

function foo( callback ) {
  callback();
}

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

foo( function(){ baz('param') });
Answer

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");
Answer

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);
});
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.