jQuery in Action

190
CHAPTER 7
Extending jQuery with custom plugins
7.2.3 Taming complex parameter lists
Most plugins tend to be simple affairs that require few, if any, parameters. We've
seen ample evidence of this in the vast majority of the core jQuery methods and
functions, which either take a small handful of parameters or none at all. Intelli-
gent defaults are supplied when optional parameters are omitted, and parame-
ter order can even take on a different meaning when some optional parameters
are omitted.
The
bind()
method is a good example; if the optional data parameter is omit-
ted, the listener function, which is normally specified as the third parameter, can
be supplied as the second. The dynamic and interpretive nature of JavaScript
allows us to write such flexible code, but this sort of thing can start to break down
and get complex (both for page authors and ourselves as the plugin authors) as
the number of parameters grows larger. The possibility of a breakdown increases
when many of the parameters are optional.
Consider a somewhat complex function whose signature is as follows:
function complex(p1,p2,p3,p4,p5,p6,p7) {
This function accepts seven arguments; let's say that all but the first are
optional. There are too many optional arguments to make any intelligent
guesses about the intention of the caller when optional parameters are omitted
(as we saw with the
bind()
method). If a caller of this function is only omitting
trailing parameters, this isn't much of a problem because the optional trailing
arguments can be detected as nulls. But what if the caller wants to specify
p7
but
let
p2
through
p6
default? Callers would need to use placeholders for any omit-
ted parameters and write
complex(valueA,null,null,null,null,null,valueB);
Yuck! Even worse is a call such as
complex(valueA,null,valueC,valueD,null,null,valueB);
along with other variations of this nature. Page authors using this function are
forced to carefully keep track of counting nulls and the order of the parameters;
plus, the code is difficult to read and understand.
But short of not allowing so many options to the caller, what can we do?
Again, the flexible nature of JavaScript comes to the rescue; a pattern that
allows us to tame this chaos has arisen among the page-authoring communities--
the options hash.


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

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