Lesson Monday

The jQuery section of our address book application is becoming a little cumbersome. Let's refactor to improve its readability and efficiency. After all, we always want to write clean, easy-to-read code with well-separated business and user interface logic. It's easier to read, easier to collaborate on, and generally appears much more professional in nature.

By pulling some of the code into functions outside of the event listener we can actually pre-process it before the document is ready. Then, for the code within the event listener, we can simply call the pre-processed functions.

For example, we can create a function to reset the fields:

js/scripts.js
...
function resetFields() {
    $("input#new-first-name").val("");
    $("input#new-last-name").val("");
    $("input.new-street").val("");
    $("input.new-city").val("");
    $("input.new-state").val("");
}
...

Then, we can remove the lines of code previously responsible for resetting the fields from the form submit callback, and simply call resetFields() instead. Easy enough!


Completed GitHub addressBook Repo, Including Optional Refactoring

Tips


  • Commonly re-used lines of jQuery code may also be turned into methods.
  • For instance: You could remove code responsible for emptying form fields after form submission into a function outside of the submit event listener, then call the function in the submit event listener instead.

Example


function resetFields() {
    $("input#new-first-name").val("");
    $("input#new-last-name").val("");
    $("input.new-street").val("");
    $("input.new-city").val("");
    $("input.new-state").val("");
}