如何扩展jquery.插件超过多个文件

how to expand jquery.plugin over multiple files

本文关键字:文件 插件 jquery 何扩展 扩展      更新时间:2023-09-26

我现在的插件变得非常大(现在刚刚超过8000行),我想知道是否有一种方法可以将它分类到不同的文件中。

就像node.js中的require函数一样,但是对于jquery,所以它会被分类到更多的文件中,从而更清晰地排列。

正如@jcubic提到的,你需要把你的代码分成单独的模块/功能。

将所有方法存储在某种类型的方法对象中(当然也可以在插件名称空间中)。这也可以很容易地添加到另一个文件中,甚至可以从另一个文件扩展。

var methods = (function ($) {
    return {
        init       : function () { initMethod(); },
        another    : function () { anotherMethod(); },
        thirdThing : function () { thirdThing(); },
        etcEtc     : function () { etcEtc(); }
    };
}(jQuery));

我强烈推荐使用方法调用的方式来创建jQuery插件,这将利用这个对象。

$.fn.pluginName = function (method) {
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' + method + ' does not exist on jQuery.tooltip');
    }
};

现在一切都分开了,你可以通过$('whatever').pluginName('methodhere');等来调用你的模块