4

I've made a small scrollbar jQuery plugin. It has a pretty standard implementation: $(selector).drollScroll({options});, complete with default values. The trick is that I'd like the user to be able to set these defaults ahead of time, so that for larger sites (I'm developing this for a larger site) future users can easily get identical scrollbars without specifying the parameters each time.

I'd really like to allow the user to do this without first instantiating a jQuery object, so via something like $.drollScrollDefaults({options}).

So far I have this:

(slimmed down to only the essentials for your reading pleasure)

(function($)
{
    var defaults = {
        content                :   ".drollScrollBowl",
        scrollBoxClassName     :   "drollScrollShoal",
        scrollbarClassName     :   "drollScrollPole",
        thumbClassName         :   "drollScrollTrollThumb",
        scrollbarOpacity       :   1,
        scrollbarFadeTime      :   300,
        scrollbarTimeToLive    :   1000,
        alwaysVisible          :   true,
        autoFade               :   false,
        overrideBoxStyling     :   false,
        overrideBarStyling     :   false,
        overrideThumbStyling   :   false,
        scrollWidthConstant    :   false
    };

    $.drollScrollDefaults = function(options)
    {
        $.extend(defaults, options);
    };

    $.fn.drollScroll = function(options)
    {
        var opts;

        return this.each(function()
        {
            // we want opts to be its own object in case someone edits it later
            opts = $.extend({}, defaults, options);

            $(this).data("drollScroll", {options : opts});
        });
    };
})(jQuery);

Now this actually works, but this line

$.drollScrollDefaults = function(options)

seriously can't be how it's supposed to be done. It feels hacked; I feel like I must be doing it wrong, like I should be using the (totally mystical to me) prototype of $ or something. Is this it? Am I right already? What is the best way to achieve this? Should I even be doing this!?

4

2 回答 2

4

我看不出有什么问题,这并不比分配像我使用的全局函数window.number_format(我构建自己的工具包)更糟糕。既然您希望用户能够调用$.drollScrollDefaults,那么这就是您应该分配的内容。

于 2013-07-11T19:38:28.213 回答
1

我通常在函数上定义它,例如,

$.fn.myplugin = function() { ... your plugin here ... };
$.fn.myplugin.defaults = { ... defaults here ...};

主要是因为我的大多数插件都可以称为$.myplugin$().myplugin()

在您的插件内部和外部访问它$.fn.myplugin.defaults

于 2013-07-11T19:39:16.870 回答