Created
June 12, 2011 10:56
-
-
Save chuckbergeron/1021429 to your computer and use it in GitHub Desktop.
jQuery Promise / Deferred functions in sequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>JS Sequence Test</title> | |
<script src="jquery-1.6.1.min.js"></script> | |
</head> | |
<body> | |
<div id="green-box" style="width:100px;height:100px;background:#484;margin:0 0 10px 0;display:none"> | |
</div> | |
<div id="red-box" style="width:100px;height:100px;background:#822;margin:0 0 10px 0;display:none"> | |
</div> | |
<div id="blue-box" style="width:100px;height:100px;background:#288;margin:0 0 10px 0;display:none"> | |
</div> | |
<script> | |
var deferred = $.Deferred(), | |
chained = deferred; | |
// Authenticates the user if the extra requires auth & he is not already authenticated | |
if ( true == true ) | |
chained = chained.pipe( authenticate ); | |
// If the Extra is a placeholder, gets its content | |
if ( true == true ) | |
chained = chained.pipe( prepareExtra, [ true ] ); | |
// When the two optional methods are resolved, shows the extra | |
chained.done( function() { $( "#blue-box" ).fadeIn( 1000 ); } ); | |
// Resolves the initial element on the chain so that the others might proceed (?) | |
deferred.resolve(); | |
function authenticate(){ | |
var d = $.Deferred(); | |
$("#green-box").fadeIn( 1000, function(){ | |
d.resolve(); | |
} ); | |
return d.promise(); | |
}; | |
function prepareExtra( arg ){ | |
var s = $.Deferred(); | |
$("#red-box").fadeIn( 1000, function(){ | |
s.resolve(); | |
} ); | |
return s.promise(); | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment