jQuery Deferred Objects

Deffered objects, promises, parameters

by deshpandeakhil

HTML

<input id="btnResolve" type="button" value="Resolve"/>
<input id="btnReject" type="button" value="Reject"/>
<input id="btnState" type="button" value="State"/>
<div id="output"></div>
<hr/>
<input type="button" id="btnPromise" value="Promise Demo"/>
<p>Ready..</p>
<div class="demo">1</div>
<div class="demo">2</div>
<div class="demo">3</div>
<div class="demo">4</div>

CSS

.demo{height:50px; width:50px;background-color:blue; float:left; margin:2px; font-size:x-large; text-align:center;}

JavaScript

// a deferred object is for holding and calling a queue of success/failure/complete callbacks
// an ajax call allows us to give success, error and complete handlers. However, it doesnt allow for a case where we want to call a success handler based on some condition. For that we have to program ourselves some kind of if else block. Moreover, we can not change the condition at any time, that is once the ajax call is made the handler is set, if in between the ajax call this condition changes, ajax can not accommodate that.
// deferred objects allows multiple callback registrations and also allows for the registration at any time i.e during creation, execution or after completion
var deferred = $.Deferred();
var f = function(arg) {
    $("#output").append(arg + "<br/>");
};
$(function() {
    $("#btnResolve").click(function() {
        if (deferred.state() === "pending") f(deferred.resolve().state());
    });
    $("#btnReject").click(function() {
        if (deferred.state() === "pending") f(deferred.reject().state());
    });
    $("#btnState").click(function() {
        f(deferred.state());
    });

    //Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.
    $("#btnPromise").click(function() {
        $('p').append("Started..");
        $('.demo').each(function(i) { 
            $(this).fadeIn().fadeOut(1000 * (i + 1));
        });
        
        $('.demo').promise().done(function(){
            $('p').append("Finished..");
        });
    });
});