如何使用jquery-boilerplate提供对jQuery插件的公共访问?

时间:2016-02-19 00:41:21

标签: javascript jquery design-patterns jquery-plugins jquery-boilerplate

我正在尝试jQuery团队在其网站的jquery-boilerplate中提供的learn plugin section模式。

我提供了对Advanced Plugin Concepts部分中学习的默认设置的公共访问权限。下面的代码是一个如何使用公共访问的简单示例:

$.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提供对插件的公共访问?如果有可能,我该怎么做?

这是我正在测试的代码:

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

1 个答案:

答案 0 :(得分:0)

$.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