passing arguments to callback

点点圈 提交于 2019-12-11 22:16:53

问题


How can I pass arguments to a callback function in this specific scenario.

I have a function that gets an object with callbacks like this

function doSomething({ callbackSuccess : myFunction, callbackError : myOtherFunction})

how can I pass arguments to myFunction or to myOtherFunction?

Like, if myOtherFunction gets a msg parameter like this

function myOtherFunction(msg) {
   alert(msg);
}

Thanks in advance


回答1:


Simplest of all:

function dosomething(callback) {
    //some code-poetry;
    callback(1, 2, 3); //the callback is back!!!
}

function foo(a, b, c) {//this will be my callback
    alert("I got some parameters")
}

dosomething(foo); //the function call

Best explanation for a callback function:Check this

A simple defination would be:the callback function is called at a certain point in the future when some code or a function completes execution.




回答2:


Just like you pass them to any other function:

function doSomething(callbacks) {
    callbacks.callbackSuccess('foo', 'bar');
}

If you mean you want to pass them "at the time of passing them into doSomething":

doSomething({ callbackSuccess : function () { myFunction('foo'); }, ... });



回答3:


Try this -

// function def
function doSomething(a) {
}

// calling function
doSomething({
    callbackSuccess : function() {
        myFunction(msg);
    },
    callbackError : myOtherFunction
});


来源:https://stackoverflow.com/questions/18615285/passing-arguments-to-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!