Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery should I use multiple ajaxStart/ajaxStop handling

Tags:

jquery

Maybe there is no difference, but is either way better than the other (or perhaps a mysterious 'third' way better than both!)...


first:

var startTime;

$(document).ready(function() {

    $("#lbl_ajaxInProgress").ajaxStart(function() {
        // store the current date/time...
        startTime = new Date();
        // update labels
        $(this).text('Yes');
        $("#lbl_ajaxCallTime").text("-");
    });

    $("#lbl_ajaxInProgress").ajaxStop(function() {
        // update labels
        $(this).text('No');
        $("#lbl_ajaxCallTime").text(myFunctionThatCalculatesTime(startTime));
    });

});

second:

var startTime;

$(document).ready(function() {

    $("#lbl_ajaxInProgress").ajaxStart(function() {
        // update labels
        $(this).text('Yes');
    });

    $("#lbl_ajaxInProgress").ajaxStop(function() {
        // update labels
        $(this).text('No');
    });

    $("#lbl_ajaxCallTime").ajaxStart(function() {
        // store the current date/time...
        startTime = new Date();
        // update labels
        $(this).text("-");
    });

    $("#lbl_ajaxCallTime").ajaxStop(function() {
        // update labels
        $(this).text(myFunctionThatCalculatesTime(startTime));
    });

});
like image 431
davidsleeps Avatar asked Jun 30 '09 05:06

davidsleeps


1 Answers

An interesting fact is that ajaxStart, etc. are actually just jQuery events. For instance:

$("#lbl_ajaxInProgress").ajaxStart(function() {
  // update labels
  $(this).text('Yes');
});

is equivalent to:

$("#lbl_ajaxInProgress").bind("ajaxStart", function() {
  // update labels
  $(this).text('Yes');
});

This means that you can also attach namespaces to ajaxStart/ajaxStop, etc. Which also means that you can do:

$("#lbl_ajaxInProgress").unbind("ajaxStart ajaxStop");

You could also do:

$("#lbl_ajaxInProgress").bind("ajaxStart.label", function() {
  // update labels
  $(this).text('Yes');
});

$("#lbl_ajaxInProgress").bind("ajaxStop.label", function() {
  // update labels
  $(this).text('No');
});

And then:

$("#lbl_ajaxInProgress").unbind(".label");

Cool, huh?

like image 179
Yehuda Katz Avatar answered Sep 19 '22 15:09

Yehuda Katz