Thursday, October 20, 2011

Javascript JQuery passing events weirdness

Back in the day I wrote some pretty cool Javascript, but I got more into a middle layer software world and had not touched UI for a long time.

In the meantime Javascript came a long way with the new JQuery language so I thought I would take a crack at it.
So I found this site http://docs.jquery.com/How_jQuery_Works and started to work on the example and I immediately discovered something that I am sure is understandable, but I don't understand how it works.

The example given is this:

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
     });
   </script>
 </body>
 </html>


Which worked but I immediately wanted to refactor those anonymous functions to make it more readable so I created this:


function ClickIt()
{
$("a").click(AlertIt(event));

}

function AlertIt(event)
{
alert("As you can see, the link no longer took you to jquery.com");
event.preventDefault();
}

$(document).ready(ClickIt());


The problem was the when I ran the new version the "event" object passed into the AlertIt(event) was null.  Odd, so after much playing around I finally discovered that I needed to call AlertIt  with no paramaters and it worked. So why is that ?  Feel free to comment.