views:

72

answers:

1

I don't know if anyone ELSE has noticed this, but I noticed the jQuery samples I see on MS tend to use a different format:

<script type="text/javascript">  

  $( domReady );  

  function domReady() {  
     $('#btn').click( showMessage );  
  }  

  function showMessage() {  
     $('#message').fadeIn('slow');  
  }  
</script> 

Isn't this the same as:

$(document).ready( function() {

  $('#btn').click( showMessage );  

  function showMessage() {  
     $('#message').fadeIn('slow');  
  }  

});

Is there any advantage of using one syntax over the other?

I will admit, the MS way does look cleaner.

+4  A: 

The only real difference is readability and organization.

It's technically the same as

$( function() {

  $('#btn').click( showMessage );  

  function showMessage() {  
     $('#message').fadeIn('slow');  
  }  

});

which is shorthand for $(document).ready(...)

David Hogue
I've always wondered how that shorthand works. `$(document).ready(...)` I understand. I guess jQuery is expecting a delegate or anonymous function?
Atømix
The main jQuery function $() checks to see if the typeof the parameter is a function. If it is, it adds it as an event handler to document.ready. If it is something else it uses it as a selector.I think this is what actually does it: if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); }
David Hogue