First jQuery Plugin: TagCloud
This is my first jQuery plugin. Can I get some pointers? It's currently not working...
; (function($) {
$.fn.tagCloud = function(options) {
开发者_StackOverflow社区 options = options || {};
var maxPercent = options['maxPercent'] || 150;
var minPercent = options['minPercent'] || 100;
var retrieveCount = options['retrieveCount'] || function(element) { return $(element).attr('rel'); };
var apply = options['apply'] || function(element, size) { $(element).attr('style', 'font-size:' + size + '%;'); };
var max = null;
var min = null;
var tagElements = this;
tagElements.each(function(element) {
count = retrieveCount(element);
max = (max == null || count > max ? count : max);
min = (min == null || min > count ? count : min);
});
var multiplier = (maxPercent - minPercent) / (max - min);
tagElements.each(function(element) {
count = retrieveCount(count);
size = (minPercent + (count - min) * multiplier);
apply(element, size);
});
}
})(jQuery);
Usage: $('a.tag').tagCloud();
make use of a static set of defaults instead of hard coding them. that way a user can override them withough havingto set them in the call for example:
$.fn.tagCloud.defaults = {
maxPercent: 150,
minPercent: 100,
countCallback: function(element){return $(element).attr('rel');},
applyCallback: function(element, size) { $(element).attr('style', 'font-size:' + size + '%;');}
};
And then in the very beginning of your plugin you would replace alot of those var declarations with a simple:
var o = $.extend($.fn.tagCloud.defaults, options||{});
then you would access everything with o.*
or o['*']
id also make some of you logic into encapsulated methods.. i typically only want/expect to see one this.each() block for the primary logic.
Also as an aside i believe if your selector doesnt have any elements in its collection youre going to be dividing by 0 or NaN which is generally a no-no. If im correct you might want to default min/max to 1 or do a simple check to make sure that the collection length is > 0 and bail out if it isnt depending on what you want it to do.
I figured it out:
; (function($) {
$.fn.tagCloud = function(options) {
options = options || {};
var maxPercent = options['maxPercent'] || 150;
var minPercent = options['minPercent'] || 100;
var retrieveCount = options['retrieveCount'] || function(element) { return $(element).attr('rel'); };
var apply = options['apply'] || function(element, size) { $(element).attr('style', 'font-size:' + size + '%;'); };
var max = null;
var min = null;
var tagElements = this;
tagElements.each(function(index) {
var count = retrieveCount(this);
max = (max == null || count > max ? count : max);
min = (min == null || min > count ? count : min);
});
var multiplier = (maxPercent - minPercent) / (max - min);
tagElements.each(function(index) {
var count = retrieveCount(this);
size = (minPercent + (count - min) * multiplier);
apply(this, size);
});
}
})(jQuery);
精彩评论