jQuery in Action

The jQuery plugin authoring guidelines
189
When creating plugins for our own use, we're usually aware of what other plu-
gins we'll use; it's an easy matter to avoid any naming collisions. But what if we're
creating our plugins for public consumption? Or what if our plugins, that we ini-
tially intended to use privately, turn out to be so useful that we want to share them
with the rest of the community?
Once again, familiarity with the plugins that already exist will go a long way in
avoiding
API
collisions, but we also encourage gathering collections of related
functions under a common prefix (similar to the proposal for filenames) to avoid
cluttering the namespace.
Now, what about conflicts with that
$
?
7.2.2 Beware the $
"Will the real
$
please stand up?"
Having written a fair amount of jQuery code, we've seen how handy it is to use
the
$
alias in place of
jQuery
. But when writing plugins that may end up in other
people's pages, we can't be quite so cavalier. As plugin authors, we have no way of
knowing whether a page author intends to use the
$.noConflict()
function to
allow the
$
alias to be usurped by another library.
We could employ the sledgehammer approach and use the
jQuery
name in
place of the
$
alias, but dang it, we like using
$
and are loath to give up on it
so easily.
Section 6.2 discussed an idiom often used to make sure that the
$
alias referred
to the
jQuery
name in a localized manner without affecting the remainder of the
page, and this little trick can also be (and often is) employed when defining
jQuery plugins as follows:
(function($){
//
// Plugin definition goes here
//
})(jQuery);
By passing
jQuery
to a function that defines the parameter as
$
,
$
is guaranteed to
reference
jQuery
within the body of the function.
We can now happily use
$
to our heart's content in the definition of the plugin.
Before we dive into learning how to add new elements to jQuery, let's look at
one more technique plugin authors are encouraged to use.


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.