So I have an object
var ajaxOptions = {
url: ajaxurl,
type: 'POST',
async: false,
success: function (retval) {
if (!JSON.parse(retval))
{
alert("Error occurred.");
}
else
{
jQuery('#member-modal').modal('hide');
location.reload();
}
},
cache: false,
contentType: false,
processData: false
};
which I want to reuse in several pieces of my code, like
var theseOptions = ajaxOptions;
theseOptions.data = new FormData($('#thisform')[0]);
$.ajax(theseOptions);
// ... somewhere else in code ...
var thoseOptions = ajaxOptions;
thoseOptions.data = new FormData($('#thatform')[0]);
thoseOptions.someOtherOption = "hehehe";
$.ajax(thoseOptions);
// ... somewhere else in code ...
var poopOptions = ajaxOptions;
poopOptions.data = new FormData($('#poopform')[0]);
$.ajax(poopOptions);
The problem is that, as I understand, my var
s are actually references to the existing ajaxOptions
, so that, for example, when I run
$.ajax(poopOptions);
the key-value pair someOtherOptions : "hehehe"
is still there. In reality I would have to do something like
var theseOptions = ajaxOptions;
theseOptions.data = new FormData($('#thisform')[0]);
$.ajax(theseOptions);
delete thoseOptions.data; // now ajaxOptions is back to what it originally was
// ... somewhere else in code ...
var thoseOptions = ajaxOptions;
theseOptions.data = new FormData($('#thatform')[0]);
theseOptions.someOtherOption = "hehehe";
$.ajax(thoseOptions);
delete thoseOptions.data; delete thoseOptions.someOtherOption; // // now ajaxOptions is back to what it originally was
// ... somewhere else in code ...
var poopOptions = ajaxOptions;
poopOptions.data = new FormData($('#poopform')[0]);
$.ajax(poopOptions);
delete poopOptions.data; // now ajaxOptions is back to what it originally was
or maybe I would have to do something like
function getAjaxBaseOptions ( )
{
return {
url: ajaxurl,
type: 'POST',
async: false,
success: function (retval) {
if (!JSON.parse(retval))
{
alert("Error occurred.");
}
else
{
jQuery('#member-modal').modal('hide');
location.reload();
}
},
cache: false,
contentType: false,
processData: false
};
}
var theseOptions = getAjaxBaseOptions();
theseOptions.data = new FormData($('#thisform')[0]);
$.ajax(theseOptions);
// ... somewhere else in code ...
var thoseOptions = getAjaxBaseOptions();
thoseOptions.data = new FormData($('#thatform')[0]);
thoseOptions.someOtherOption = "hehehe";
$.ajax(thoseOptions);
// ... somewhere else in code ...
var poopOptions = getAjaxBaseOptions();
poopOptions.data = new FormData($('#poopform')[0]);
$.ajax(poopOptions);
This seems a little ridiculous. Is there really no native way in Javascript of making a direct copy of an object? WTF?