How to execute a function whose name was passed as a parameter of another function, à la callback?

Asked

Viewed 67 times

2

I created this function in order to abstract the calls $.ajax() to be performed at various different times. One of its parameters is the name of one of the functions I would like to be performed in case of success.

However, how should I make the call to this "callback"?

function submitData(myCallback) {
    $.ajax({
        success: function(res){
            myCallback(res);
        }
    });

}

function processarResponse(response) {

}

Finishing with the help received from Valdeir Psr: the passage of the parameter 'myCallback' must be done passing the name and signature of the callback:

submitData(processarResponse(response));
  • Thanks for editing; I liked your concision.

2 answers

1


Just use nome_da_funcao(), for example:

function exec( fun ) {
  fun("World") //Passando parâmetros
}

exec( function() {
  console.log("Success")
} )

exec( function(res) {
  console.log(`Hello ${res}`)
} )

Based on your example:

function submitData(myCallback) {
    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        success: function(res){
            myCallback(res);
        }
    });
}

submitData(function(res) {
  console.log( "Título do POST: ", res.title )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You still use the apply or the call, for example:

myCallback.call(null, res)
myCallback.apply(null, [res])

Example:

function submitData(myCallback) {
    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        success: function(res){
            myCallback.call(null, res)
        }
    });
}

submitData(function(res) {
  console.log( "Título do POST: ", res.title )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  • Could you please show me how I would do this in the example of the initial question? It’s kind of embarrassing, but I couldn’t apply your concept to the example given.

  • @jCintra I updated the example

1

Just remove the quotes that will work:

function submitData(myCallback) {
    $.ajax({
        success: function(res){
            myCallback(res);
        }
    });
}

myCallback must be able to receive the parameter passed

Browser other questions tagged

You are not signed in. Login or sign up in order to post.