Isaiah
Isaiah

Reputation: 1902

Javascript - Replace callback with function, including parameters

Though Stackexchange Meta forbids me to start with "Hi,", I think there is no substantial harm to being friendly.

Hi,

I use the following piece of code,

while (!success) {
    new Magister(chosenSchool, username, password).ready(function(error){
        /* Code here using the error variable above */
    });
}

but JSLint warnes me that it would be a bad practice to define functions inside a loop.
However, using the following code, doesn't work either.

function checkLogin(error) {
    /* Code here using the error variable above */
}
while (!success) {
    new Magister(chosenSchool, username, password).ready(checkLogin(error));
}

This results into Uncaught ReferenceError: error is not defined. How can I not redefine a function, but still passing the error as in the original function(error){...}?
I tried various methods, but it won't budge for me.

Thanks in advance!

Upvotes: 1

Views: 235

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

Just don't call the function:

new Magister(chosenSchool, username, password).ready(checkLogin);

ready expects a function object, so you have to pass chechLogin itself instead of calling it and passing its return value (which is likely undefined).

How can I not redefine a function, but still passing the error as in the original function(error){...} ?

Maybe that's where the confusion lies. You are actually not passing error at all. The argument is passed by the caller, which is ready.


One nice feature of JavaScript is that you can simple replace variables with the literal representation of their value (in most cases).

So if we look at

new Magister(...).ready(checkLogin(error));

and replace checkLogin with it's value (the function) it becomes

new Magister(...).ready(function checkLogin(error){...}(error));

However, that doesn't look like the first version at all! Suddenly a wild (error) appears at the end of our function definition.

Lets go the other way round:

new Magister(...).ready(function(error){...});
// becomes
new Magister(...).ready(function checkError(error){...});
// becomes
function checkError(error) { ... }
new Magister(...).ready(checkError);

Much better.

Upvotes: 1

Related Questions