如何使用 jquery-样板提供 public 对 jQuery 插件的访问权限?

How to provide public access to jQuery plugin using jquery-boilerplate?

我正在试用他们网站的jquery-boilerplate pattern over the one the jQuery team provides in the learn plugin section

我提供 public 访问默认设置的权限,正如我在 Advanced Plugin Concepts 部分中了解到的那样。下面的代码是如何使用 public 访问权限的简单示例:

$.fn.hilight = function( options ) {
    var opts = $.extend( {}, $.fn.hilight.defaults, options );

};

$.fn.hilight.defaults = {
    foreground: "red",
    background: "yellow"
};

// Example of usage
$.fn.hilight.defaults.foreground = "blue";

$( ".hilightDiv" ).hilight();

$( "#green" ).hilight({
    foreground: "green"
});

我想知道,是否可以使用 jquery-boilerplate 提供对插件的 public 访问权限?如果可能的话,我该怎么做?

这是我正在测试的代码:

;( function( $, window, document, undefined ) {
    "use strict";

    var pluginName = "boilerplateTest",
        defaults = {
            random: "random text",
            random2: {
                one: 1,
                two: 2
            }
        };

    function Plugin( element, options ) {
        this.element = element;
        this.mainSettings = $.extend( {}, defaults, options );
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend( Plugin.prototype, {
        init: function() {
            var cfg = this.mainSettings;

            this.printToConsole( cfg );
        },
        printToConsole: function( e ) {
            console.log( e );
        }
    } );

    $.fn[ pluginName ] = function( options ) {
        return this.each( function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName,
                new Plugin( this, options ) )
            }
        } );
    };
} )( jQuery, window, document );

$.fn[ pluginName ]实际上和$.fn.hilight是一样的,所以你可以直接替换。

;( function( $, window, document, undefined ) {
    "use strict";

    var pluginName = "boilerplateTest";

    $.fn[ pluginName ] = function( options ) {
        return this.each( function() {
            if ( !$.data( this, "plugin_" + pluginName ) ) {
                $.data( this, "plugin_" + pluginName,
                new Plugin( this, options ) )
            }
        } );
    };

    $.fn[ pluginName ].defaults = {
            random: "random text",
            random2: {
                one: 1,
                two: 2
            }
        };

    function Plugin( element, options ) {
        this.element = element;
        this.mainSettings = $.extend( {}, $.fn[ pluginName ].defaults, options );
        this._defaults = $.fn[ pluginName ].defaults;
        this._name = pluginName;
        this.init();
    }

    $.extend( Plugin.prototype, {
        init: function() {
            var cfg = this.mainSettings;

            this.printToConsole( cfg );
        },
        printToConsole: function( e ) {
            console.log( e );
        }
    } );

} )( jQuery, window, document );

参见this JSFiddle