jon3laze
jon3laze

Reputation: 3196

Writing jQuery plugin that accepts method and options

I am following the instructions for authoring a plugin from the jQuery docs. I am trying to keep my calls in the same namespace as they instruct in section 6.1 however I also need to be able to pass through more options with each call.

What I'd like to do

$('#element').myFunction({
    method: 'method1',
    option1: 'option1',
    option2: 'option2'
});

What I have currently

(function($) {

    var methods = {
        init: function(options) {
           //initialization
        },
        method1: function(options) {
            var settings = $.extend({
                'option1' = 'option default',
                'option2' = 'option 2 default'
            }, options);
            //use settings for given method ex: settings.option1, settings.option2
        }
    };

    $.fn.myFunction(options) {
        //method logic
        if(methods[options.method]) {
            return methods[options.method].apply(this, Array.prototype.slice.call(arguments, 1)); //I'm thinking I need to do something here to pass through the options to the methods???
        } else if (typeof options.method === 'object' || !options.method) {
            return methods.init.apply(this, arguments); //or possibly here?
        } else {
            $.error('Method ' + options.method + ' does not exist on jQuery.myFunction');
        }
    };
})(jQuery);

I've not been doing front end web development for sometime and am trying to brush back up on it, however the method logic section is somewhat confusing to me. I need to understand what processing is happening on the methods[options.method].apply(). I know this is where each method is being called but am just not sure as to where additional options would be passed.

[update1]

I have read some more on what's happening with the apply() and believe that it passes through the object and any other arguments. I've tried changing it to methods[options.method].apply(this, options); however this doesn't seem to have corrected my issue.

[update2]

I now have my code working by making the following changes

 var methods = {
    init: function(options) {
       //initialization
    },
    method1: function(element, options) {
        var settings = $.extend({
            'option1' = 'option default',
            'option2' = 'option 2 default'
        }, options);
        //use settings for given method ex: settings.option1, settings.option2
         element.each(function() {

         };
    }
};

$.fn.myFunction(options) {
    //method logic
    if(methods[options.method]) {
        return methods[options.method](this, options); // apply(this, Array.prototype.slice.call(arguments, 1)); //I'm thinking I need to do something here to pass through the options to the methods???
    } else if (typeof options.method === 'object' || !options.method) {
        return methods.init.apply(this, options); // arguments); //or possibly here?
    } else {
        $.error('Method ' + options.method + ' does not exist on jQuery.myFunction');
    }
};

I am going to leave this open for a few days though, anyone that wants to explain what the original code was trying to do vs. my changes I will accept that as the answer.

Upvotes: 0

Views: 938

Answers (1)

napolux
napolux

Reputation: 16084

Here's a template I've found on the Internet and that I'm using to not start from scratch...

// keep all your code in a closure
(function($)
{
    // name your plugin - try to make it unique
    $.fn.wTooltip = function(option, settings)
    {
        // check if user is setting/getting properties manually after plugin creation
        if(typeof option === 'object')
        {
            settings = option;
        }
        else if(typeof option === 'string')
        {
            var data = this.data('_wTooltip');

            // this will check if plugin has already been initialized for this element
            if(data)
            {
                if($.fn.wTooltip.defaultSettings[option] !== undefined)
                {
                    if(settings !== undefined){
                        if(option == 'title') data.content.html(settings);
                        data.settings[option] = settings;
                        return true;
                    }
                    else return data.settings[option];
                }
                else return false;
            }
            else return false;
        }

        // extend user settings with default settings
        settings = $.extend({}, $.fn.wTooltip.defaultSettings, settings || {});

        // iterate through all elements and return them to maintain jQuery method chaining
        return this.each(function()
        {
            var elem = $(this);

            // create copy of settings object allowing us to make individual adjustments
            // this ensures that only values for current element are changed
            var $settings = jQuery.extend(true, {}, settings);
            $settings.title = settings.title || elem.attr('title') || 'No title set';

            // create a tooltip object
            var tooltip = new Tooltip($settings);

            // we would typically run our generation code here
            tooltip.generate();

            // run some code here
            // try to keep as much of the main code in the prototype methods as possible
            // focus on just setting up the plugin and calling proper methods from here

            // store the tooltip object for later reference - setters/getters
            elem.data('_wTooltip', tooltip);
        });
    }

    // provide default settings
    // setting it up like this allows a developer to modify defaults like so:
    // $.fn.wTooltip.defaultSettings.color = 'white';
    $.fn.wTooltip.defaultSettings = {
        position    : 'mouse',
        color       : 'black'
    };

    // create our tooltip "class"
    // this will store the unique individual properties for each tooltip
    function Tooltip(settings)
    {
        this.tooltip = null;
        this.settings = settings;

        return this;
    }

    // prototype the tooltip class
    // this will contain methods shared amongst all tooltips
    // DO NOT keep any unique tooltip properties here
    Tooltip.prototype = 
    {
        generate: function()
        {
            // use local reference of this
            // this will be important when using in other closures like event closures
            var $this = this;

            // return the tooltip in case its already been defined for the current element 
            if($this.tooltip) return $this.tooltip;

            //code
        },

        someFunc: function()
        {
            //code
        }
    }
})(jQuery);

wTooltip is the name you should personalize to create a unique plugin

Upvotes: 2

Related Questions