0

在此期间,我的自定义函数数量以及我的 jQuery 插件的初始化调用数量不断增加,导致视觉和功能混乱。

我的自定义功能

我正在寻找一种将自定义函数组织到库中的方法。

  • 我应该创建一个对象并将它们组织为方法吗?

例如

(function($) {   
    $.myCUSTOMOBJECT = {};
    $.fn.myCUSTOMOBJECT = function(settings) {
        var var1 = ...
        var var2 = ...
        var var3 = ...
        function onTextSelectionDoSomething() {...}
        function onTextClickDoSomethingElse() {...}
    }

});

我的贡献函数

我有 contrib jQuery 库作为 fancybox、jcarousel、parallax

  • 是否建议将它们合并到一个缩小文件中?
4

2 回答 2

1

For the sake of simplicity, I wouldn't bother storing your custom work on the jQuery namespace to begin with. I take this approach;

I will have one file like this:

( function () {

    var myNamespace = {
        fancybox: { ... },
        jcarousel: { ... }
    };

    window.myNamespace = myNamespace;

})();

Then on a per website/app basis I would use my namespace like so;

( function ( $, ns ) {

    $( document ).ready( function () {

        $( '.lightbox' ).on( 'click', ns.fancybox.init );

    });

})( jQuery, myNamespace );

The purpose of this is try to remove your framework from the rest of your code

于 2013-02-22T14:11:17.383 回答
1

Custom functions

I usually create a utils object that contains all my little useful functions like trim etc. I treat it a bit like a loose underscore. For all my generic functions and methods that have nothing to do with the specifics of my site or application, I will include these in a plugins.js file (based on the implementation in HTML5 boilerplate).

Contrib functions

I will usually include all relatively small plugins in the plugins.js file along with my own. Larger files that I may want to debug or update separately, that have very distinct functionality, I will keep as separate files in a /vendor/ or /libs/ folder. This makes it easy to swap in new versions and see if anything breaks, or swap in unminified versions with the same filenames to debug in detail, etc.

On minification

If you're dealing with a small enough site, where almost all the scripts are necessary on the first page, you will probably want to minify most if not all of your scripts into one for production. This shouldn't affect how you organise scripts in development though.

于 2013-02-22T14:11:54.230 回答