I am using jQuery to handle something. It relates to many class or id having a prefix ‘receive’ in its name. Now I want to duplicate those function, but with the prefix ‘send’. It looks like this
function onSelectAddress() {
$('#receive-address').on('click', function() {
$('#receive-dropdown').show();
$('#receive-address').addClass('box-click');
});
$('#send-address').on('click', function() {
$('#send-dropdown').show();
$('#send-address').addClass('box-click');
});
}
I don’t want to copy paste and change ‘receive’ to ‘send’ line by line. Is there any way to handle this problem?
3
Answers
One way I can think of to optimize your code is to create a generic function that takes a
receive
andsend
as a parameter and handles both cases. Something like(code is untested but you get the idea):Refactor by creating a generic function which accepts a prefix:
Note the use of backticks for string interpolation.
Then use it:
This code uses a common class "address" for both ‘receive-address’ and ‘send-address’ elements and utilizes the data-action attribute to determine whether it’s a ‘receive’ or ‘send’ action. This way, you avoid duplicating the code and make it more maintainable.