I have been working on refactoring my client side JavaScript validations on an application. My tech lead gave me some illuminating tips on how to refactor my non-DRY code. Here is an example of the pre-refactored code.
// Initial State for Form$('.your_info').hide();// validationsvarfirst_name=$('input#order_first_name');varlast_name=$('input#order_last_name');varemail=$('input#order_email');// event listenersfirst_name.keyup(function(){validateFirstName();});last_name.keyup(function(){validateLastName();});email.keyup(function(){validateEmail();});functionvalidateFirstName(){varfirst_name_val=first_name.val();if(first_name_val.length==0){first_name_error.show().text("First name needed.").addClass('error_class');returnfalse;}else{first_name_error.hide();returntrue;}}functionvalidateLastName(){varlast_name_val=last_name.val();if(last_name_val.length==0){last_name_error.show().text("Last name needed.").addClass('error_class');returnfalse;}else{last_name_error.hide();returntrue;}}functionvalidateEmail(){varemail_val=email.val();if(email_val.length==0){email_error.show().text("Email needed.").addClass('error_class');returnfalse;}else{email_error.hide();returntrue;}}
Clearly, this is not DRY and will easily get out of comtrol. However, using HTML data attributes solves this problem. Here is a good summary about data attributes by John Resig.
We can dynamically call the data attribute for each element. For example, the error_name value the keyup event(m) will console.log (=> First name, m). The call method allows us to refactor all of our keyup event listeners into one method. The call method as defined by the Mozilla guide "calls a function with a given this value and arguments provided individually."