As you evolve, you will write more and more complex JavaScript files. You will of course use various plug-ins to not reinvent the wheel. All of this existing code might already have Event Handlers that attached to various elements already. If you dont have a good habit of writing clean code you will waste a lot of time trying to figure out why certain events are not working the way they should. I will show you how you should be creating your event handlers in this article so that you are guaranteed to not interfere with any existing code or plug-in you might have to work with.

In jQuery this is a very simple click event that prints to the console when clicked:

$('#some-button-id').click(function(){
    console.log('I have been clicked');
});

First thing you should notice is that the callback function inside the click function is an anonymous function. There is no easy way of cleaning it up after you have done with it, whenever that might be. Thats why it is in general bad practice to use anonymous functions. so lets improve our code:

var my_click_event = function() {
    console.log('I have been clicked');
}
$('#some-button-id').click(my_click_event);

Perfect, it already looks cleaner and now we have a reference variable we can use for that specific click event. Now if I wanted to remove that specific click event I would just:

$('#some-button-id').unbind('click', my_click_event);

This technique is very useful when you have so many click events assigned to a selector and you can’t just call $('#some-button-id').unbind('click') because it would get rid of all the click events.