jQuery in Action

186
CHAPTER 7
Extending jQuery with custom plugins
Over the course of the previous chapters, we've seen that jQuery gives us a large
toolset of useful commands and functions; we've also seen that we can easily tie
these tools together to give our pages whatever behavior we choose. Sometimes that
code follows common patterns we want to use again and again. When such patterns
emerge, it makes sense to capture these repeated operations as reusable tools that
we can add to our original toolset. In this chapter, we explore how to capture these
reusable fragments of code as extensions to jQuery.
But before any of that, let's discuss why we'd want to pattern our own code as
extensions to jQuery in the first place.
7.1 Why extend?
If you've been paying attention at all while reading through this book, as well as
to the code examples presented within it, you undoubtedly have noted that
adopting jQuery for use in our pages has a profound effect on how script is writ-
ten within a page.
The use of jQuery promotes a certain style for a page's code, frequently in the
guise of forming a wrapped set of elements and then applying a jQuery com-
mand, or chain of commands, to that set. When writing our own code, we can
write it however we please, but most experienced developers agree that having all
of the code on a site, or at least the great majority of it, adhere to a consistent style
is a good practice.
So one good reason to pattern our code as jQuery extensions is to help main-
tain a consistent code style throughout the site.
Not reason enough? Need more? The whole point of jQuery is to provide a set
of reusable tools and
API
s. The creators of jQuery carefully planned the design of
the library and the philosophy of how the tools are arranged to promote reusabil-
ity. By following the precedent set by the design of these tools, we automatically
reap the benefit of the planning that went into these designs--a compelling sec-
ond reason to write our code as jQuery extensions.
Still not convinced? The final reason we'll consider (though it's quite possible
others could list even more reasons) is that, by extending jQuery, we can leverage
the existing code base that jQuery makes available to us. For example, by creating
new jQuery commands (wrapper methods), we automatically inherit the use of
jQuery's powerful selector mechanism. Why would we write everything from
scratch when we can layer upon the powerful tools jQuery already provides?
Given these reasons, it's easy to see that writing our reusable components as
jQuery extensions is a good practice and a smart way of working. In the remainder


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

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