Jquery calling a callback function in a custom function

后端 未结 3 874
一生所求
一生所求 2021-02-08 10:00

I have a custom function and I want to add a callback function to it, i looked through the other questions but I couldn\'t really find the answer for my problem. So basically it

3条回答
  •  盖世英雄少女心
    2021-02-08 10:39

    You would call it like this (passing the callback function as an argument):

     myfunction(myCallbackFn);
    

    Notice that there are no parentheses after the function name when passing a reference to the function as an argument. This does not invoke the function, but just passes a reference to it which can then be called later from within your custom function.

    You would define your function and then call the callback function in it like this:

    function myfunction(cb) {
        cb(arg1, arg2);
    }
    

    Note, there are multiple methods of actually calling the callback function from within your custom function. If you just need to call it normally and don't care about the this argument, you can just use:

    cb();
    

    If you want to set the this argument to something, you can use this:

    cb.call(thisArg, arg1, arg2);
    

    If you want to pass along your current arguments or pass an array of arguments and set the this argument, you would use this:

    cb.apply(thisArg, argArray);
    

    References on .call() and .apply().


    Your current code has a javascript error in this area:

    test(rand_gyumolcs, link, callback){
        callback();
    }; 
    

    This is not legal javascript. I don't know what you're trying to do, but this looks like half of a function declaration and half of a function call. If you just want to call the test function, you would just use this:

    test(rand_gyumolcs, link, callback);
    

    Inside of test, if you want the callback function to be called after the animation is complete, then you would have to hook the completion function of the animation and call the callback then.

提交回复
热议问题