将实用程序函数放入JQuery插件的正确位置在哪里?

时间:2014-02-04 00:44:35

标签: jquery jquery-plugins

假设我有一个我创建的jQuery插件(from the jquery site):

(function ( $ ) {

    $.fn.greenify = function( options ) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#556b2f",
            backgroundColor: "white"
        }, options );

        // Greenify the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
        });

    };

}( jQuery ));

但是现在我可能需要一些更大的函数来促进我的插件操作,哪里是放置这些函数并保持我的代码整洁,可读和可测试的最佳位置?

例如,我认为本地化函数是个坏主意,如下所示:

(function ( $ ) {

    $.fn.greenify = function( options ) {

        // This would be bad becase too many of these and my code will be clutered.
        var aHelperFunctionThatIsHuge = function () {
          // A lot of code here...
        };

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#556b2f",
            backgroundColor: "white"
        }, options );

        // Greenify the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
        });

    };

}( jQuery ));

这根本不起作用:

(function ( $ ) {

    $.fn.greenify = function( options ) {

        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#556b2f",
            backgroundColor: "white"
        }, options );

        // Greenify the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
        });

    };

    // ideal but doesnt work
    $.fn.greenify.aHelperFunctionThatIsHuge = function () {
          // A lot of code here...
    };


}( jQuery ));

那么我应该把它们放在哪里?

由于

1 个答案:

答案 0 :(得分:0)

在插件功能之上,在IIFE中:

(function ( $ ) {

    var aHelperFunctionThatIsHuge = function () {
      // A lot of code here...
    };

    $.fn.greenify = function( options ) {

    };

}( jQuery ));