pufAmuf
pufAmuf

Reputation: 7795

Callback in a callback?

I wrote a callback (I believe it's called) like this:

hugeFadeIn();

It's a simple code to fade in some content so that I don't reuse the same code over and over again.

I then wanted to execute some code after hugeFadeIn finishes... So I did this:

hugeFadeIn(){
    //la la la
});

And that was wrong, so I did this:

$(hugeFadeIn(){
    //la la la
});

And I'm still getting errors. What am I doing wrong? Thanks everyone :)

Edit As requested, the body of the hugeFadeIn function:

function hugeFadeIn() {
    $("#huge-loader").fadeIn("fast");
}

Upvotes: 1

Views: 372

Answers (5)

jONGsKiE777
jONGsKiE777

Reputation: 156

when i write a function, i usually put a parameter for callback :

function myFunction(param1, callback_param){

    alert(param1); // do stuff here 

    if(typeof(callback_param) == "function"){

        callback_param();

    }
}

and here's how i call it.

myFunction('Hello World', function(){
     alert('Yes!, this is the World, how can i help you?');
});

hope this contributes. thanks

Upvotes: 1

jack-all-trades
jack-all-trades

Reputation: 282

function hugeFadeIn(time, callback) {
    $('.something').fadeIn(time, callback);
}

So then

hugeFadeIn(500, doAjaxWhathever);

or something like this for async

$.HugeFade = function(item, time, callback) { $(item).fadeIn(time); callback();}
$.HugeFade('#myDiv', 1500, myCallback);

But if you're using hugeFadeIn as a callback, you can't do this

$('#myDiv').load(url, hugeFadeIn(500, callback2)); //wrong
// it should be..
$('#myDiv').load(url, function(){hugeFadeIn(500, callback2)});

Upvotes: 1

Slawomir Pasko
Slawomir Pasko

Reputation: 907

if you need to do something with the same element just put call of second method after first one

hugeFadeIn();
someOtherMethodCall();

If you need to deal with other element on the page and you need to force calling second method after first method finish - use delay method (http://api.jquery.com/delay/)

hugeFadeIn();
someOtherMethodCall();

someOtherMethodCall(time){
  $('#some-id').delay(time).hide();
}  

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160181

If you want to run something after hugeFadeIn finishes, you need to pass your callback in.

function hugeFadeIn(after) {
    // whatever
    after();
}

(If hugeFadeIn does the fade itself and doesn't rely on calling something that itself takes a callback.)

Edit after OP edit.

function hugeFadeIn(after) {
    $("#huge-loader").fadeIn("fast", after);
}

Upvotes: 2

Seth
Seth

Reputation: 6260

close...

hugeFadeIn(function() {

    alert('My callback is running');

});

Then in hugeFadeIn()

hugeFadeIn = function( fn ) {

    fn();

}

Upvotes: 1

Related Questions