Yongke Bill Yu Yongke Bill Yu - 10 days ago 6
Ajax Question

In jQuery how to wait for specific value on variable

I have an variable

var IsAjaxing;


I set it to true everytime a ajax is fired on the page. And then set it to false when ajax is finished;

I am building a SafeAjaxing event so work would only be done when the page is not ajaxing:

// safe-ajaxing: Triggers when no ajax is running
$($fieldRenderPageDOM).on("safe-ajaxing", '.field-render', function(e, work) {
$.when({ IsAjaxing: false }).done(work);
});


This doesn't seem to wait, work is always called immediately.

It would be called like this:

$fieldDOM.trigger("safe-ajaxing", function () {
$fieldDOM.trigger("do-work");
$fieldDOM.trigger("do-some-more-work);
});

Answer

You should use promises for this purpose:

var IsAjaxing = function(){
    var defer = $.Deferred().resolve();

    return {
        On: function(){
            defer = $.Deferred();
        },
        Off: function(){
            defer.resolve();
        },
        Promise: function() {
            return defer.promise();
        },
        IsOn: function() {
            return defer.state() == "pending";
        },
        IsOff: function() {
            return defer.state() != "pending";
        }
    };
}();

And then your event will be:

// safe-ajaxing: Triggers when no ajax is running
$($fieldRenderPageDOM).on("safe-ajaxing", '.field-render', function(e, work) {
    $.when(IsAjaxing.Promise()).done(work);
});

Each time when you start ajax request run:

IsAjaxing.On();

Each time when you finish ajax run:

IsAjaxing.Off();

To check the current state of IsAjaxing, call the IsOn and IsOff function.

Comments