Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bahaddinyasar/3487467 to your computer and use it in GitHub Desktop.
Save bahaddinyasar/3487467 to your computer and use it in GitHub Desktop.
Deferred Callbacks w/ jQuery - Real World Example
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
});
@bahaddinyasar
Copy link
Author

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment