0
\$\begingroup\$

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);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 25, 2012 at 2:23
\$\endgroup\$
1
  • \$\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\$ Commented Mar 30, 2012 at 20:02

1 Answer 1

1
\$\begingroup\$

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.

answered Feb 29, 2012 at 16:39
\$\endgroup\$
1
  • 1
    \$\begingroup\$ or just !== undefined \$\endgroup\$ Commented Mar 30, 2012 at 18:17

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.