jQuery in Action

192
CHAPTER 7
Extending jQuery with custom plugins
settings
variable ends up with all possible option default values superseded by
any explicit values specified by the page author.
Note that we guard against an
options
object that's
null
or undefined with
||{}
, which supplies an empty object if
options
evaluates to
false
(as we know
null
and
undefined
do).
Easy, versatile, and caller-friendly!
We'll see examples of this pattern in use later in this chapter and in jQuery
functions that will be introduced in chapter 8. But for now, let's finally look at how
we extend jQuery with our own utility functions.
7.3 Writing custom utility functions
In this book, we use the term utility function to describe functions defined as prop-
erties of
jQuery
(and therefore
$
). These functions are not intended to operate on
DOM
elements--that's the job of methods defined to operate on a jQuery
wrapped set--but to either operate on non-element JavaScript objects or per-
form some other nonobject-specific operation. Some examples we've seen of
these types of function are
$.each()
and
$.noConflict()
.
In this section, we'll learn how to add our own similar functions.
Adding a function as a property to an
Object
instance is as easy as declaring
the function and assigning it to the
object
property. (If this seems like black
magic to you and you have not yet read through the appendix, now would be a
good time to do so.) Creating a trivial custom utility function should be as easy as
$.say = function(what) { alert('I say '+what); }
And in truth, it is that easy. But this manner of defining a utility function isn't
without its pitfalls; remember our discussion in section 7.2.2 regarding the
$
?
What if some page author is including this function on a page that uses Prototype
and has called
$.noConflict()
? Rather than add a jQuery extension, we'd create
a method on Prototype's
$()
function. (Get thee to the appendix if the concept of
a method of a function makes your head hurt.)
This isn't a problem for a private function that we know will never be shared,
but even then, what if some future changes to the pages usurp the
$
? It's a good
idea to err on the side of caution.
One way to ensure that someone stomping on
$
doesn't also stomp on us is not
using the
$
at all. We could write our trivial function as
jQuery.say = function(what) { alert('I say '+what); }


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

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