views:

88

answers:

1

Hello, I seem to regularly write jQuery code of a pattern similar to this:

Fade Out ==> Do Something Behind the Scenes ==> Fade In
Illustrated below:

/// <reference path="jquery-1.4.2.js" />
/// <reference path="jquery-1.4.2-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
var fade = "slow";

$(document).ready(function () {

    // Some event occurs
    $("#Trigger").change(function () {
        var id = $(this).find(":selected").val();        

        // Fade out target while I do something
        $("#Target").fadeOut(fade, function () {
            if (id != "") {

                // Do Something
                $("#Target").load(
                    "/Site/Controller/Action/"+id, null,
                    function () {

                        // Fade in Target
                        $("#Target").fadeIn(fade);
                    });
            }
        });
    });
});

This works fine, but the callback hierarchy gets pretty deep and I'm just wondering if there's an easier way to do this or a better technique that doesn't result in so many levels of callbacks

+1  A: 

Use jQuery's .queue

$("#Target")
    .fadeOut()
    .queue(function() {
        if (id != "")
            // Do Something
            $(this).load(
                "/Site/Controller/Action/"+id, null,
                $(this).dequeue
            );
        else
            $(this).dequeue();
    })
    .fadeIn()
Eric
Oh interesting, I hadn't seen that! Nice tip!
TJB