CodeLikeBeaker
CodeLikeBeaker

Reputation: 21312

JavaScript callback function not handling pass-through parameters

I've been banging my head against the wall for a bit on this one, and I can't quite seem to figure it out. I know there are a ton of other very similar questions out there, and I've looked at just about all of them, and none of them seems to have the answer that I'm looking for (but then again, I could be blind today).

So I have a JavaScript function that I'm passing a function in as a parameter to do a callback. My function has a parameter in it, so when I do the callback, my parameter that I pass in needs to follow through when the callback is invoked.

However, when I add the 2nd parameter, the value is always undefined.

Sample Code:

<div style="padding: 15px;">
<a href ="#" onclick="FirstFunction('first param');">test</a>
</div>

//call the first function from the click event and pass in the value
function FirstFunction(param1) {
    //call my process function, but pass in a function as a parameter with the value from param1
    myProcessFunction(function(){SecondFunction(param1)});
    return false;
}

function SecondFunction(param1, param2) {
    alert(param1 + ', ' + param2);
}

function myProcessFunction(callback) {
    if (typeof callback == 'function') {
        //call my passed in function, return the original values, along with a new value into my "SecondFunction"
        callback(this, 'second param');
    }
}

Any help would be appreciated.

I've tried:

callback.call(this, 'param 2')

callback(arguments, 'param 2')

callback.call(arguments, 'param 2')

And probably about 20 other combinations... so I'm at guess work now.

Here is my jsFiddle:

http://jsfiddle.net/FVsDK/8/

EDIT

Thank you Jani, here is a working solution in jsFiddle: http://jsfiddle.net/FVsDK/9/

Upvotes: 1

Views: 1324

Answers (1)

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

The error is caused because of your callbacks are a bit of a mess :)

myProcessFunction(function(){SecondFunction(param1)});

This calls myProcessFunction with a callback function function() { ... }

Thus, in myProcessFunction, callback(this, 'second param'); is calling the above function, which takes no parameters at all.

If you want secondFunction to take the parameters from myProcessFunction, you must pass that instead of your anonymous callback:

myProcessFunction(SecondFunction)

Here, SecondFunction's parameters would be this and 'second param'.

Or alternatively if you want to pass param1 to it, you can also do this:

myProcessFunction(function(a, b) { SecondFunction(param1, a, b); })

Here, SecondFunction's parameters would be the value of param1, this and 'second param'.

Upvotes: 3

Related Questions