(Not sure if I am using the correct terminology, in Python that is called a tuple. Hope it makes sense.)
I would like to refactor the following method. The only difference is the enddate/startdate respectively, therefore there is no need to repeat the code.
function datepicker_reload(source, isPast){
if(isPast){
$(source).find('.date_picker').datepicker({
endDate: new Date(),
format: $('#locale').text(),
weekStart:1,
calendarWeeks:'True',
autoclose: 'True',
todayHighlight: 'True'
});
}
else{
$(source).find('.date_picker').datepicker({
startDate: new Date(),
format: $('#locale').text(),
weekStart:1,
calendarWeeks:'True',
autoclose: 'True',
todayHighlight: 'True'
});
}
}
I was wondering if I could put the common values as a tuple together:
var options = { format: $('#locale').text(),
weekStart:1,
calendarWeeks:'True',
autoclose: 'True',
todayHighlight: 'True' };
Then add the one additional keypair in there: (However this step seems to be completely off, how do i achieve it?)
if(isPast)
options += {endDate: new Date()}
else
options += {startDate: new Date()}
and then pass the whole tuple to the function:
$(source).find('.date_picker').datepicker(options);
is this possible?
The correct syntax in javascript for what you're trying to do is:
if(isPast){
options["endDate"] = new Date();
}else{
options["startDate"] = new Date();
}
You are just setting an object's property.
Note: options.endDate = new Date(); (dot notation) would also work, however it does not work if the property you're adding to the object contains spaces, operators, or other special chars.
Note 2: I'm assuming you don't really want to clone the object but just to add a property to it, javascript objects are mutable.
With jQuery, the conventional way to do this is to use extend:
$.extend(options, { endDate: new Date() });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With