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);
\$\endgroup\$
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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ or just !== undefined \$\endgroup\$
    – Chad
    Mar 30 '12 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.