hide - Understanding jQuery
hide - Understanding jQuery
hide - Understanding jQuery
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
There is, indeed, a third way to bind and unbind event handlers. An example can be seen below:<br />
var handler = function()<br />
{<br />
alert(‘The quick brown fox jumps over the lazy dog.’);<br />
};<br />
$(‘#orange’).bind(‘click’, handler);<br />
$(‘#orange’).unbind(‘click’, handler);<br />
By naming our event handler (so that it is no longer a function closure) and separating it from<br />
the bind and unbind functions, we are able to explicitly tell <strong>jQuery</strong> to work with the original<br />
location in memory of the object that we created.<br />
This means that you will be binding and unbinding only click events assigned by your script.<br />
Imagine if some other script (not developed by you) assigns a click event handler to the<br />
HTML element with ID “orange” and that we unbind it by accident using our code. We would<br />
interrupt the flow of that other script.<br />
But Javascript code can be very sensitive to syntax being used. There is one more precaution<br />
you should be aware of when binding and unbinding your event handlers. Consider the code<br />
below:<br />
$(‘#orange’).bind(‘click’, function()<br />
{<br />
alert(‘The quick brown fox jumps over the lazy dog.’);<br />
});<br />
// This will NOT unbind the event handler attached above<br />
$(‘#orange’).unbind(‘click’, function() {<br />
alert(‘The quick brown fox jumps over the lazy dog.’);<br />
});<br />
The unbind event in the example above will not actually unbind the event handler attached<br />
with the bind function right above it. Why not? Because the first function created a function<br />
closure located at an arbitrary address in memory.<br />
The second function did the same thing. Essentially, we are telling Javascript to unbind an<br />
event handler we have just created, yet, instead of giving the unbind function the handle to<br />
that event, in the second example we are trying to unbind a brand new function we are creating<br />
at the same time.<br />
Nameless functions that we have specified “on the fly” will always be stored at a new, unique<br />
address in memory even if their contents are exactly the same.<br />
96