ianace
ianace

Reputation: 1635

jquery callback

hi can someone explain to me the concept of jquery's callback kinda stuck on this simple code

$(document).ready(function(){
    bar('',function(){
        foo();
    });         
});

function foo()
{
    alert('foo');
}

function bar()
{
    alert('bar');
}

so that foo() get executed first then bar(), but with the code above, only foo() gets executed and bar does not execute.

here is a jsfiddle link

Upvotes: 3

Views: 7087

Answers (1)

no.good.at.coding
no.good.at.coding

Reputation: 20371

Functions are first-class members in JavaScript and as such, can be assigned to variables and passed as arguments to other functions. The idea of a callback function is that one (or more) of parameters a function receives is a function reference which can be invoked under certain conditions. In your case, you're calling bar with two arguments but never doing anything with those parameters in bar. JavaScript doesn't call back functions automatically, you as the programmer must do that.

This is probably what you want:

$(document).ready(function(){
    bar('',function(){ //this anonymous function maps to the parameter b in bar(a,b)
        foo(); //missing ; can lead to hard to track errors!
    });         
});


function foo()
{
    alert('foo');
}

//accept two parameters
// in this example code, given the call to bar() above, a will map to '' and b to the anonymous function that calls foo()
function bar(a, b) 
{
    alert('bar');
    if(typeof b === 'function'){ //check if b is a function
        b(); //invoke
    }
}

Edit

@Jared's suggestion definitely makes more sense - changed if(b) to if(typeof b === 'function'){ before invoking b

Upvotes: 8

Related Questions