Created
June 9, 2011 16:39
-
-
Save chuckbergeron/1017139 to your computer and use it in GitHub Desktop.
jQuery Promise / Deferred / AJAX methods 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
var Tab = function() { | |
/* | |
* EXTRAS | |
*/ | |
var Extras = function() { | |
var show = function( id ) { | |
var extra = $( "#" + id ), | |
d = $.Deferred(); | |
chained = d; | |
// If the Extra is a placeholder, gets its content | |
var div = extra.find( "div:first" ); | |
if ( div.length ) | |
chained = chained.pipe( prepareExtra( div ) ); | |
// Authenticates the user if: | |
// * the extra requires auth | |
// * he is not already authenticated | |
if ( extra.attr( "requires-auth" ) != undefined && !config.user_is_authenticated ) | |
chained = chained.pipe( authenticate ); | |
// When the two optional methods are resolved, show the content | |
chained.done( function() { extra.fadeIn( 500 ) } ); | |
d.resolve(); | |
}; | |
var prepareExtra = function( div ) { | |
return $.post( div.attr( "href" ), {}, function( data ) { | |
div.html( data ) | |
} ); | |
}; | |
}(); | |
var authenticate = function() { | |
var d = $.Deferred(); | |
FB.ui( { method: "permissions.request", perms: "email" }, function( response ) { | |
if ( response.session ) | |
$.post( "/authenticated/create_or_log_in_user", { | |
access_token : response.session.access_token | |
}, function() { | |
config.user_is_authenticated = true; | |
d.resolve(); | |
} ); } ); | |
return d.promise(); | |
}; | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pipe
takes functions, not Promises. Try changing yourprepareExtra
to:So that it returns a function that will be called when the previous Deferred is resolved.