Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Password Confirmation Form Perform: Part 1

How is using a Function keeping code more DRY?

With instructors function the code now becomes 11 lines, when this can be done in only 10 lines of code using the example below. Personally I find it easier to read without the use of a function, but with me being new to programming, perhaps there's another reason for this which I'm not aware of?

$password.on('focus', function(){
  $(this).next().show();
  $(this).keyup(function(){
    if ($(this).val().length < 8) {
      $(this).next().show();
    } else {
      $(this).next().hide();
    }
  });
});

3 Answers

Steven Parker
Steven Parker
231,275 Points

Your code doesn't do the same thing as the code in the video.

The video code establishes the same handler for both the focus and keyup events, and it does so only once for each.

But your code has a very different handler for focus, which includes repeatedly attaching an additional keyup handler during every event.

Code can only be considered "DRYer" if it still does the same job.

Is my code wrong? I know it works, but am I using the wrong approach?

Steven Parker
Steven Parker
231,275 Points

It might seem to "work", but it's clearly not doing the same thing. But in this case, the functional difference isn't obvious from the external behavior.

It would not be a good idea to repeatedly attach another handler the way your code does.

This code is not repeatedly resetting the keyup handler. It's attaching an additional keyup handler each time the element receives focus.

The code is consuming more and more memory each time the focus event happens.

Steven Parker
Steven Parker
231,275 Points

Good point. I rephrased my wording.

OK, many thanks, but does the function in the instructors code not repeatedly reset the handler when it's called upon?

Forgive me, but I'm still a bit confused.

Steven Parker
Steven Parker
231,275 Points

No, in the video the handler for focus and the handler for keyup are both established only one time, and they both use the same function ("passwordEvent") each time an event occurs. That function only hides or shows the message following the input element.

@Jason Anello Thanks for the explanation.... this makes much more sense to me now.