Lesson Wednesday

Address Book Refactoring (Optional)

Our jQuery section is getting a bit cumbersome and we might consider ways to improve its readability and efficiency with some additional refactoring.

By pulling some of the code into functions outside of the event binding, we can pre-process it before the document is ready. Then, for the code within the event binding, 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("");
}
...

Now we can remove those lines from the form submit callback and simply call them with resetFields().

Completed GitHub addressBook repo, including refactor

Sample code

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("");
}
...