编写接受方法和选项的jQuery插件

时间:2012-06-28 16:39:40

标签: jquery function plugins methods

我正在遵循jQuery文档中的说明for authoring a plugin。我试图将我的调用保持在他们在6.1节中指示的相同名称空间中,但是我还需要能够在每次调用时传递更多选项。

我想做什么

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

我目前所拥有的

(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);

我有一段时间没有进行前端Web开发,并且我正在尝试重新开发它,但是方法逻辑部分对我来说有点混乱。我需要了解methods[options.method].apply()上正在进行的处理。我知道这是调用每个方法的地方,但我不确定将传递其他选项的位置。

[UPDATE1]

我已经阅读了更多关于apply()发生了什么的信息,并且相信它会通过对象和任何其他参数。我已经尝试将其更改为methods[options.method].apply(this, options);,但这似乎没有纠正我的问题。

[UPDATE2]

我现在通过进行以下更改来使我的代码正常工作

 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');
    }
};

我打算将这个开放几天但是,任何想要解释原始代码尝试做什么的人和我的更改我会接受这个作为答案。

1 个答案:

答案 0 :(得分:2)

这是我在互联网上找到的一个模板,我用它不是从头开始......

// 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 是您应该个性化的名称,以创建一个独特的插件

相关问题