modern-web-design-and-development

(Brent) #1
1 $('#table td').bind('click contextmenu', {message: 'hello!'},
function(e) {

(^2) alert(e.data.message);
3 });
As you can see, we’re passing into our callback a set of variables for it to
have access to, in our case the variable message.
Yo u m i g h t w o n d e r w h y w e w o u l d d o t h i s. W h y n o t j u s t s p e c i f y a n y va r i a b l e s
we want outside the callback and have our callback read those? The answer
has to do with scope and closures. When asked to read a variable,
JavaScript starts in the immediate scope and works outwards (this is a
fundamentally different behavior to languages such as PHP). Consider the
following:
1 var message = 'you left clicked a TD';
2 $('#table td').bind('click', function(e) {
(^3) alert(message);
4 });
5 var message = 'you right clicked a TD';
6 $('#table td').bind('contextmenu', function(e) {
(^7) alert(message);
8 });
No matter whether we click the with the left or right mouse button,
we will be told it was the right one. This is because the variable message is
read by the alert() at the time of the event firing, not at the time the
event was bound.
If we give each event its own “version” of message at the time of binding
the events, we solve this problem.

Free download pdf