How to pass a callback as a parameter into another

2019-01-06 09:50发布

I'm new to ajax and callback functions, please forgive me if i get the concepts all wrong.

Problem: Could i send a callbackfunction as a parameter to another function that will execute the callback?

function firstFunction(){
    //some code

    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

function secondFunction(var1, var2, callbackfunction) {
    params={}
    if (event != null) params = event + '&' + $(form).serialize();

    // $.post() will execute the callback function
    $.post(form.action,params, callbackfunction);
}

5条回答
Explosion°爆炸
2楼-- · 2019-01-06 09:55

Yes of course, function are objects and can be passed, but of course you must declare it:

function firstFunction(){
    //some code
    var callbackfunction = function(data){
       //do something with the data returned from the ajax request
     }
    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).

查看更多
贼婆χ
3楼-- · 2019-01-06 10:08

Example for CoffeeScript:

test = (str, callback) ->
  data = "Input values"
  $.ajax
    type: "post"
    url: "http://www.mydomain.com/ajaxscript"
    data: data
    success: callback

test (data, textStatus, xhr) ->
  alert data + "\t" + textStatus
查看更多
欢心
4楼-- · 2019-01-06 10:14

Yup. Function references are just like any other object reference, you can pass them around to your heart's content.

Here's a more concrete example:

function foo() {
    console.log("Hello from foo!");
}

function caller(f) {
    // Call the given function
    f();
}

function indirectCaller(f) {
    // Call `caller`, who will in turn call `f`
    caller(f);
}

// Do it
indirectCaller(foo); // alerts "Hello from foo!"

You can also pass in arguments for foo:

function foo(a, b) {
    console.log(a + " + " + b + " = " + (a + b));
}

function caller(f, v1, v2) {
    // Call the given function
    f(v1, v2);
}

function indirectCaller(f, v1, v2) {
    // Call `caller`, who will in turn call `f`
    caller(f, v1, v2);
}

// Do it
indirectCaller(foo, 1, 2); // alerts "1 + 2 = 3"

查看更多
ゆ 、 Hurt°
5楼-- · 2019-01-06 10:16

If you google for javascript callback function example you will get Getting a better understanding of callback functions in JavaScript

This is how to do a callback function:

function f() {
    alert('f was called!');
}

function callFunction(func) {
    func();
}

callFunction(f);
查看更多
甜甜的少女心
6楼-- · 2019-01-06 10:18

Also, could be simple as:

if( typeof foo == "function" )
    foo();
查看更多
登录 后发表回答