jQuery in Action
Adding new wrapper methods
215
return name.replace(/thumbnail/,'photo');
},
nextControl: null,
previousControl: null,
firstControl: null,
lastControl: null
}, callerSettings || {});
settings.photoElement = $(settings.photoElement);
settings.thumbnails = this.filter('img');
settings.thumbnails.each(function(n){this.index = n;});
settings.current = 0;
settings.thumbnails.click(function(){ showPhoto(this.index); });
settings.photoElement.click(function(){
showPhoto((settings.current + 1) % settings.thumbnails.length);
});
$(settings.nextControl).click(function(){
showPhoto((settings.current + 1) % settings.thumbnails.length);
});
$(settings.previousControl).click(function(){
showPhoto((settings.thumbnails.length + settings.current - 1) %
settings.thumbnails.length);
});
$(settings.firstControl).click(function(){
showPhoto(0);
});
$(settings.lastControl).click(function(){
showPhoto(settings.thumbnails.length - 1);
});
showPhoto(0);
return this;
};
var showPhoto = function(index) {
settings.photoElement
.attr('src',
settings.transformer(settings.thumbnails[index].src));
settings.current = index;
};
})(jQuery);
Boy, it seemed longer than 45 lines when we were working through it, didn't it?
This plugin is typical of jQuery-enabled code; it packs a big wallop in some
compact code. But it serves to demonstrate an important set of techniques--
using closures to maintain state across the scope of a jQuery plugin and to enable
the creation of private implementation functions that plugins can define and use
without resorting to any namespace infringements.
using closures to maintain state across the scope of a jQuery plugin and to enable
the creation of private implementation functions that plugins can define and use
without resorting to any namespace infringements.