jQuery in Action
Using other libraries with jQuery
165
This part declares a function and encloses it in parentheses to make an expression
out of it, resulting in a reference to the anonymous function being returned as the
value of the expression. The function expects a single parameter, which it names
out of it, resulting in a reference to the anonymous function being returned as the
value of the expression. The function expects a single parameter, which it names
$
; whatever is passed to this function can be referenced by the
$
identifier within
the body of the function. And because parameter declarations have precedence
over any similarly named identifiers in the global scope, any value defined for
over any similarly named identifiers in the global scope, any value defined for
$
outside of the function is superseded within the function by the passed argument.
The second part of the idiom
(jQuery)
performs a function call on the anonymous function passing the
jQuery
object as
the argument.
As a result, the
$
name refers to the
jQuery
object within the body of the func-
tion regardless of whether it's already defined by Prototype or some other library
outside of the function. Pretty nifty, isn't it?
outside of the function. Pretty nifty, isn't it?
When employing this technique, the external declaration of
$
isn't available
within the body of the function.
A variant of this idiom is also frequently used to form a third syntax for
declaring a ready handler in addition to the means that we already examined in
section 1.3.3. Consider the following:
section 1.3.3. Consider the following:
jQuery(function($) {
alert("I'm ready!");
});
By passing a function as the parameter to the
jQuery
function, we declare it as a
ready handler as we saw in section 1.3.3. But this time, we declare a single param-
eter to be passed to the ready handler using the
eter to be passed to the ready handler using the
$
identifier. Because jQuery
always passes a reference to
jQuery
to a ready handler as its first and only param-
eter, this guarantees that the
$
name refers to
jQuery
inside the ready handler
regardless of the definition
$
might have outside the body of the handler.
Let's prove it to ourselves with a simple test. For the first part of the test, let's
examine the
HTML
document of listing 6.2.
<html>
<head>
<title>Hi!</title>
<script type="text/javascript"
src="../scripts/jquery-1.2.1.js">
</script>
Listing 6.2 Ready handler test 1