jQuery in Action
Adding new wrapper methods
213
Outside of the plugin function, but inside the outer function, we define the
showPhoto()
function as follows:
var showPhoto = function(index) {
settings.photoElement
.attr('src',
settings.transformer(settings.thumbnails[index].src));
settings.current = index;
};
This function, when passed the
index
of the thumbnail whose full-sized photo is
to be displayed, uses the values in the
settings
object to do the following:
1
Look up the
src
attribute of the thumbnail identified by
index
2
Pass that value through the
transformer
function to convert it from a
thumbnail
URL
to a photo
URL
3
Assign the result of the transformation to the
src
attribute of the full-
sized image element
4
Record the index of the displayed photo as the new current index
But before we break our arms patting ourselves on the back for our cleverness, we
should know that there's still a problem. The
should know that there's still a problem. The
showPhoto()
function needs access
to the settings, but that variable is defined inside the plugin function and isn't
available outside of it.
available outside of it.
"Holy scoped closures, Batman! How will we get out of this one?"
We could be inelegant about it and pass
We could be inelegant about it and pass
settings
to the function as another
parameter, but we're slyer than that. Because the problem is that
settings
isn't
defined in the outer closure containing the implementation and plugin functions
the simplest solution is to move it there. Doing so won't affect its availability to all of
the inner closures, but it will ensure that it's available to both the plugin function
and the implementation function or any other implementation functions that we
might want to define. (Be aware that this technique assumes that we're only going
to have one Photomatic instance on a page--a restriction that makes sense in this
case. For more general cases, passing
the simplest solution is to move it there. Doing so won't affect its availability to all of
the inner closures, but it will ensure that it's available to both the plugin function
and the implementation function or any other implementation functions that we
might want to define. (Be aware that this technique assumes that we're only going
to have one Photomatic instance on a page--a restriction that makes sense in this
case. For more general cases, passing
settings
as a parameter would not impose
this restriction.)
So we'll add the following to the outer function:
var settings;
And remove the
var
from the statement within the plugin function as follows:
settings = $.extend({