I have the following code:
function submitHandler($link, $modal, close) {
var $form = $modal.find('#main-form');
var $submitBt = $modal.find('.block-footer button:contains("Submit")');
var oSubmit = {
$form: $form,
$modal: $modal,
action: $form.attr('data-action'),
entity: $form.attr('data-entity'),
href: $form.attr('data-href'),
row: $link.attr('data-row'),
$row: $('#row_' + $link.attr('data-row')),
$submitBt: $submitBt
};
if (!$form.valid || $form.valid()) {
$submitBt.disableBt();
$modal.removeBlockMessages()
.blockMessage('Contacting Server, please wait ... ', { type: 'loading' });
$.ajax({
url: oSubmit.href,
dataType: 'json',
type: 'POST',
data: $form.serializeArray()
})
.done(function (json, textStatus, XMLHttpRequest) {
json = json || {};
if (json.success) {
submitSuccessModal(oSubmit, json);
if (close == true) {
$modal.closeModal();
if (oSubmit.action == "Create") {
$('#createLink').prop('disabled', false);
}
}
} else {
submitFailModal(oSubmit, json);
}
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
setTimeout(function () {
$modal
.removeBlockMessages()
.blockMessage('Could not contact server, please try again', { type: 'error' });
$submitBt.enableBt();
}, 1000);
return false;
});
};
};
What’s the best way to move the functionality out of my $.ajax and out into a function for “done” and another function for “fail”. Also what parameters should I be passing to these functions? I guess what I am most confused about is what should I do about the variables I have declared at the top of my code. Should I pass these also to the external functions as in the .done I do reference some of them.
What you have to now makes use of what is known as anonymous functions. You pass a reference to an anonymous function (a function without a name) into the
doneandfailfunctions.Perhaps to better organize your code (or to make these functions shareable with other code), all you need to do is give these functions a name and move them outside the
ajax()call. We’ll call themonDoneandonFail, though you can of course call them whatever makes sense.Notice I reference them without parathesis, since I’m referring to the function object itself, and not the return value of the called function.