Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write easy to debug/maintain JavaScript Event Handlers

Event Handler can be written in mainly two ways:

<input type="button" onclick="clickFunction()" />

or

 $('#btnID).click( function(){ .. });

Someone has to debug/maintain this code at a later stage. In the first case, we can do "inspect Element" and quickly find what is executed. In the second case, we have to find the right Document Loader code to find where it is assigned.

What is the recommended way?

like image 601
srini.venigalla Avatar asked Aug 25 '26 09:08

srini.venigalla


1 Answers

The recommended way is to write an event handler (the second option). For reasoning behind this, look at "2. Don’t Write Inline Javascript" in this great article.

Furthermore, if you are looking to write code thats easier to debug, consider naming your callbacks. This way they will show up in js errors with the function name instead of "in undefined".

$('#btnID).click( function someEvent(){ .. });
like image 68
Kostia Avatar answered Aug 26 '26 21:08

Kostia