JavaScript : jQuery : Best way to add Event Handlers makes debuging easy

I work on Rails project with 20+ javascript files. I even have implement the Javascript/script response using the js.erb template. Also, I am using jQuery instead of the vanillaJs to code easily. These days I figured out that in developer mode in browsers its impossible to find the actual event handler function by pointing at any node element. It was awesomely easy when there was no jQuery or any other library.

var $links = $('.assign-to-me');
 $.each($links, function(index, item){
   $(item).on('click', function(){
     alert('Click Event Triggered')
   });
 });
'On Click' Event handler using jQuery

‘On Click’ Event handler using jQuery makes debugging nightmare

So, I suggest the following way to write the event listeners

var $links = $('.assign-to-me');
 $.each($links, function(index, item){
   item.addEventListener('click', function(){
     alert('Click Event Triggered')
   });
 });
'Click' Event handler using vanilla javascript

‘Click’ Event handler using vanilla Javascript makes debugging easy.

References:

http://www.sitepoint.com/jquery-vs-raw-javascript-3-events-ajax/

Leave a comment