Javascript callback function with parameters [dupl

2019-01-09 04:03发布

This question already has an answer here:

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?

5条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-09 04:12

Use an anonymous function:

function foo( callback ) {
  callback();
}

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

foo( function(){ baz('param') });
查看更多
小情绪 Triste *
3楼-- · 2019-01-09 04:13

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");
查看更多
可以哭但决不认输i
4楼-- · 2019-01-09 04:14

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);
});
查看更多
一夜七次
5楼-- · 2019-01-09 04:27

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);
});
查看更多
老娘就宠你
6楼-- · 2019-01-09 04:29

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

查看更多
登录 后发表回答