简体   繁体   中英

Why isn't this simple callback function working?

I'm trying to use a callback function for the first time and am having trouble getting it working. Here's a simplified version of my code:

var unsavedChanges = 1;

function saveData(callback)
{
    // save data

    if(typeof callback === "function")
    {
        unsavedChanges = 0;
        callback.apply(arguments);
    }
}

function nextStep(val)
{
    if(unsavedChanges == 1)
    {
        saveData(nextStep, val);
        return false;
    }

    console.log(val);
}

nextStep("test");

JSFiddle: http://jsfiddle.net/tXqn3/

Inside my real "saveData" function I'm saving data using $.ajax() and I have the callback in the .done() function. So, this way, if there's unsaved data on the page then it gets saved and then the original function that was called gets executed.

With this code, the value undefined gets printed out to the console when the code runs. What am I doing wrong?

Your code has two problems.

First, look at the definition of apply : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

You're missing the first argument thisArg , which is what should be used as this within the function you're applying.

Second, I don't think you actually want to pass arguments into apply. What you want is all but the first argument, since the first argument is callback . So you can use Array.prototype.slice.call(arguments).slice(1) to get all the arguments except the first, and pass this into apply .

Here's a working fiddle with these changes: http://jsfiddle.net/UkdT7/1/

If you want to use a callback that accepts arguments, the simplest, idiomatic way to do this is to pass a closure which takes care of the argument passing:

var unsavedChanges = 1;

function saveData(callback)
{
    // save data

    if(typeof callback === "function")
    {
        unsavedChanges = 0;
        callback(); // no callback.apply
    }
}

function nextStep(val)
{
    if(unsavedChanges == 1)
    {
        saveData(function () { 
            nextStep(val);
        });
        return false;
    }

    console.log(val);
}

nextStep("test");

http://jsfiddle.net/mattball/YxDkg

apply function gets the thisArg as first arugment and then array as second arguments so you need to do this

callback.apply(this,arguments);

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM