The following snippet works as expected:
function boxAnimation() {
var dfd = $.Deferred();
$('div').fadeIn('slow', dfd.resolve);
return dfd.promise();
}
$(function () {
boxAnimation().done(
function () { $(this).animate({ 'margin-top': 50 }); },
function () { $(this).animate({ 'margin-left': 150 }); },
function () { $(this).animate({ 'margin-top': 250 }); },
function () { $(this).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});
However in this one the differed object is neither rejected or resolved.
Please tell me where am I going wrong.
function boxAnimation() {
var dfd = $.Deferred();
var randomNum = Math.floor(Math.random() * 5);
$('div').fadeIn('slow', function () {
if (randomNum == 1) {
dfd.reject;
}
else {
dfd.resolve;
}
});
return dfd.promise();
}
$(function () {
boxAnimation().done(
function () { $(this).animate({ 'margin-top': 50 }); },
function () { $(this).animate({ 'margin-left': 150 }); },
function () { $(this).animate({ 'margin-top': 250 }); },
function () { $(this).animate({ 'margin-left': 350 }); }
).fail(function () { alert('failed'); });
});
my body is:
<div id='box' style='width:200px; height:200px; border:solid 1px #222222; display:none; background:#cccccc'></div>
You should call functions; currently you’re accessing them and leaving them untouched. By actually calling
reject/resolve, you are really rejecting/resolving things.In the
fadeInin the first example, you passed it without(). This is correct, because you should leave it untouched at that point. jQuery will internally call the function when the animation is done.Since in the second example the calls are already in a function that is executed when the animation is done, you should call them at that point.
Secondly, inside a
donehandler,thisis theDeferredobject. If you want to pass thediv, you can do so by passing it when rejecting/resolving: http://jsfiddle.net/PrmQR/1/.