This code is the basic structure I use for coding plugins. It's pretty standard with the settings extended and the each loop. However, now I'm working on the best way to provide setters/getters. For example, I may want to do something like:
var sp = $("#container").wScratchPad();
alert(sp.wScratchPad('size'));
sp.wScratchPad('color', '#FF0000');
sp.wScratchPad('reset');
I have my little setters/getters area below and this is what I have come up with so far. I'm looking for a nice clean standard way to do this for all future plugins, something I can just copy and paste for the most part at least. I'm looking for any input on this, particularly if there are anyways to do it cleaner and with less code.
(function($)
{
var defaultSettings =
{
//settings here
};
$.fn.wScratchPad = function(option, settings)
{
//check for setter/getters
if(typeof option === 'object')
{
settings = option;
}
else if(typeof option == 'string')
{
var sp = this.data('_wScratchPad');
var hit = true;
if(sp)
{
if(option == 'reset') sp.reset();
else if(defaultSettings[option])
{
if(settings) sp.settings[option] = settings;
else return sp.settings[option];
}
else hit = false;
}
else hit = false;
return hit;
}
settings = $.extend({}, defaultSettings, settings || {});
return this.each(function()
{
var elem = $(this);
var sp = new ScratchPad(settings);
//code here
elem.data('wScratchPad', sp);
});
}
//clasess/prototypes here
})(jQuery);
-
\$\begingroup\$ This is exactly what the jQuery Ui Widget Factory is for. It is awesome, you should use it even if you don't use anything else from jQuery ui. Go to the download customization page and select just the widget factory. It is 3.3kb minified. \$\endgroup\$George Mauer– George Mauer2012年03月30日 20:02:22 +00:00Commented Mar 30, 2012 at 20:02
1 Answer 1
The only issue I see is with this:
else if(defaultSettings[option])
If you have any boolean options or numeric options which are set to 0, this will evaluate to false and the code within the if
will not execute.
Perhaps use typeof
instead.
-
1\$\begingroup\$ or just
!== undefined
\$\endgroup\$Chad– Chad2012年03月30日 18:17:23 +00:00Commented Mar 30, 2012 at 18:17