3

I'm trying to figure out how to chain custom functions:

I have something like this:

show_loader(0, function() {
    open_box($target_open, event.value, '.wide-col', function() {
        hide_loader(function() {
            scroll_to_content($target_open, function() {
            });
            $(this).dequeue();
        });
        $(this).dequeue();
    });
    $(this).dequeue();
});

Those functions have a callback implemented that looks something like this:

function show_loader(position, callback) {
    $ajaxSpinner.fadeIn();
    status = "loading"; //some non-jQuery stuff
    if (callback) $ajaxSpinner.queue( function() {callback()} );
}

You can see the basic idea of what i'm trying to do: execute my functions after the animations inside the functions are complete.

I don't think my code is quite right. The order should be: show loader, open box, hide loader, then finally scroll to content. Instead, it seems like this is what's actually happening when i test it: show loader, hide loader, scroll to content, then open box.

How do I get that order of function calls properly queued? And am I using the keyowrd "this" in the proper context?

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
trusktr
  • 44,284
  • 53
  • 191
  • 263

1 Answers1

1

You can see the basic idea of what i'm trying to do: execute my functions after the animations inside the functions are complete.

If you use standard animation functions from jQuery, you should be able to directly pass a callback to them. E.g.:

function show_loader(position, callback) {
    $ajaxSpinner.fadeIn(callback);
    status = "loading"; //some non-jQuery stuff
}

Have a look at http://api.jquery.com and see how they work.

Update:

Here is an example that produces the desired result using queue. I'm using a newer form, where the next function to execute is passed as argument to the callback. Maybe you are doing something wrong with dequeue. Edit: I tried your code and it works fine. I guess your are not using queue properly in the other functions.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • thank you thank you thank you! I spent hours reading about .queue() including here: http://stackoverflow.com/questions/1058158/can-somebody-explain-jquery-queue-to-me/3314877#3314877 But nothing provided the exact solution i needed until your answer. Is there a way to determine if an action is completed on some object? That'd be useful for calling next() on the event of an action being completed. – trusktr Mar 06 '11 at 10:25
  • 1
    @trusktr: I guess you mean your other question? ;) – Felix Kling Mar 06 '11 at 10:40
  • @trusktr: I wouldn't do that. I assume the order of executing the functions should is fixed, so why split it up? Create a function that calls the methods in the right order. – Felix Kling Mar 06 '11 at 10:46