1 minute
Contact me

A better way to event handle

In a previous post I took at look event handling in JavaScript. The title of this post is a clue you can expect more of the same in this one.This time, my goal is to show that there is merit to spending some time refactoring and tidying up code once your idea has been stubbed out and is working, and hopefully in the following example I can make my case.

Note: there is no difference in functionality of the buttons, they just handle the click event differently.The JavaScript is heavily commented and is worth reviewing if you would like a deeper understanding of what is happening.

See the Pen Handler object in plain ol' JavaScript by Adam Harpur (@harps116) on CodePen.

a summary of what is happening

In technique one we are grabbing the element we want to listen on, then we add an event listener to that element, then we trigger a function on that event.

There is a cleaner and more explicit way, in technique two we add the 'onclick' attribute to the element and call a method of a 'handler' object which stores all potential events that could be triggered and returns the corresponding function.This greatly reducing the need to repeat code and makes the whole script more legible, not only for anyone else that reads your code but also for your future self.

This post was inspired by content fron this amazing and free course: Practical JavaScript | Watch and Code