Handling of events
If you have used jQuery before, you probably used .click()
at some point. It is used to define an event handler that will respond to a mouse click in jQuery. There are many more of those, going from keyboard input, form submission, and window resizing, but we will not go through all these. Instead we will focus on the more "low-level" functions to handle events in jQuery and explain exactly the subtle differences between them.
You would typically use some of those functions to implement the control of your games either with mouse or keyboard inputs.
.bind()
The .bind()
function is the basic way to handle events. .click()
is, for example, just a wrapper around it. The two lines of the following example have exactly the same effect:
$("#myElementId").click(function(){alert("Clicked!")}); $("#myElementId").bind('click', function(){alert("Clicked!")});
However, there is a limitation with the usage of bind
. Like all other jQuery functions, it only applies to the selected elements. Now, imagine a situation where you want to execute some task each time a user clicks a link with a given class. You would write something like this:
$(".myClass").click(function(){/** do something **/});
This will work as intended, but only for the link present in the webpage at the moment of its execution. What if you change the content of the page with an Ajax call, and the new content also contains links with this class? You will have to call this line of code again to enhance the new links!
This is far from ideal, because you have to manually track all event handlers you defined that may require to be called again later and all the places where you change the content of the page. This process is very likely to go wrong and you'll end up with some inconsistencies.
The solution to this problem is .delegate()
, which is explained in detail in the following section.
.delegate()
With .delegate()
, you give the responsibility of handling events to a parent node. This way all elements added later on as a child to this node (directly under it or not) will still see the corresponding handler execute.
The following code fixes the preceding example to make it work with a link added later on. It's implied that all those links are children of a div with the ID
attribute as page
.
$("#page").delegate( ".myClass", "click", function(){/** do something **/});
This is a very elegant way to solve the problem and it will come in very handy while creating games, for example, where you click on sprites.
Removing event handlers
If you need to remove an event handler you can simply use the .unbind()
and .undelegate()
functions.
jQuery 1.7
In jQuery 1.7, .delegate()
and .bind()
have been replaced by .on()
(and .off()
to remove the handlers). Think of it as a .delegate()
function with the capacity to behave like .bind()
. If you understand how .delegate()
works, you will have no problem to use .on()
.