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 trialjlampstack
23,932 PointsHow 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
231,275 PointsYour 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.
jlampstack
23,932 PointsOK, 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
231,275 PointsNo, 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.
jlampstack
23,932 Points@Jason Anello Thanks for the explanation.... this makes much more sense to me now.
jlampstack
23,932 Pointsjlampstack
23,932 PointsIs my code wrong? I know it works, but am I using the wrong approach?
Steven Parker
231,275 PointsSteven Parker
231,275 PointsIt 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.
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsThis 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
231,275 PointsSteven Parker
231,275 PointsGood point. I rephrased my wording.