Created
August 27, 2012 11:00
-
-
Save bahaddinyasar/3487467 to your computer and use it in GitHub Desktop.
Deferred Callbacks w/ jQuery - Real World Example
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
function saveContact( row ){ | |
var form = $.tmpl(templates["contact-form"]), | |
valid = true, | |
messages = [], | |
dfd = $.Deferred(); | |
/* | |
bunch of client-side validation here | |
*/ | |
if( !valid ){ | |
dfd.resolve({ | |
success: false, | |
errors: messages | |
}); | |
} else { | |
form.ajaxSubmit({ | |
dataType: "json", | |
success: dfd.resolve, | |
error: dfd.reject | |
}); | |
} | |
return dfd.promise(); | |
}; | |
saveContact( row ) | |
.then(function(response){ | |
if( response.success ){ | |
// saving worked; rejoice | |
} else { | |
// client-side validation failed | |
// output the contents of response.errors | |
} | |
}) | |
.fail(function(err) { | |
// AJAX request failed | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Description:
The saveContact() function first validates the form and saves the result into the variable valid. If validation fails, the deferred is resolved with an object containing a success boolean and an array of error messages. If the form passes validation, the deferred is resolved, except this time the success handler receives the response from the AJAX request. The fail() handler responds to 404, 500, and other HTTP errors that could prevent the AJAX request from succeeding.
Reference: http://www.erichynds.com/jquery/using-deferreds-in-jquery/