Working on a dynamic website that loads information from a JSON file and then populates the page with said elements.
My question has to do with event handling – as of now, I don’t see any reason as to why I would need to add event handlers inline if I could just use the equivalent jQuery handler in an external script file. I could see the argument where one would say it allows for more control over events, but would that be true?
Here are the two methods I am looking at:
Inline:
<div class="family" onclick="goToFamilyPage()">This Family</div>
External/imported script:
$(document).on('click', '.family', function() {
//do stuff
});
What would be the benifit of one of these versus the other?
7
It’s better to use event handlers. Event handlers keep JavaScript out of your HTML which is usually better for decoupling reasons. The only time in-line JavaScript is okay is if you inject it via a template. This is often done when with React.js because it generates a lot of HTML (which is arguably a template).
The benefit of the 1st approach is, as you read your HTML file you also know what happens when the div is clicked (i.e. gotoFamilyPage) without having to dig through your javascript source files, which can get quite large.
In other words, your HTML file describes both the structure and behavior of your page. This is better in my opinion. Many people cite coupling as a reason to avoid inline event handlers, yet if you ask them when was the last time coupling was a problem for them, they’d have to think hard.
Unless the code is short, your inline handlers should call a function. The function’s name should be descriptive. In your case, gotoFamilyPage() is perfect. The set of Javascript functions that is invoked from inline event handlers essentially comprise an interface that nevertheless achieves the decoupling of code and presentation.
According to me, jQuery Event handler is preferable, when you are working with binding dynamic event on basis of certain condition.
Ex.
On Employee detail form, there are multiple buttons i.e. Cancel and Save and you are enabling Cancel button on document load and Save button on once user will fill all details of Employee.
If you use javascript event handler,
<div class="family" onclick="goToFamilyPage()">This Family</div>
in this event handling mechanism, it is difficult to handle conditional event, suppose you want to allow this click event on certain condition then it is difficult to handle this.
But if you use jQuery event handler you can bind() and unbind() events conditionally.
$("#family").unbind("click");
$("#family").bind("click", function(){
// handle click
});
If you want to enable Save button click event then bind this event other wise unbind so that user won’t submit data to server.
Something to keep in mind is that you can only add one inline event on a node but you can add many via event handlers.
1