My code repeats as follows:
$("#school-name").autocomplete("/ajax/campus_ajax.php", {
width: 218,
delay: 300,
selectFirst: false,
resultsClass: 'ac_results_class',
loadingClass: 'ac_loading',
formatItem: function(data)
{
if (data[2])
{
return data[0] + '<small>' + data[2] + '</small>';
}
else
{
return data[0];
}
}
});
$("#school-name-optional").autocomplete("/ajax/campus_ajax.php", {
width: 358,
delay: 300,
selectFirst: false,
resultsClass: 'ac_results_book',
loadingClass: 'ac_loading',
formatItem: function(data)
{
if (data[2])
{
return data[0] + '<small>' + data[2] + '</small>';
}
else
{
return data[0];
}
}
});
As you can see, the two event listeners only differ in a couple of parameters. How should I shorten this code?
IMO, shortening this code makes it less readable and as configuration parameters outside the reach of DRY (Don’t Repeat Yourself).
With that said, to answer your questions, there are two quick things you could do.
First, break out the
formatIteminto a generic function instead of an anonymous function.then use:
Second, you could create the base configuration options, then extend them.