【问题标题】:Is namespace desired in a jquery plugin?jquery 插件中是否需要命名空间?
【发布时间】:2014-03-09 13:48:58
【问题描述】:

我最喜欢的创建 jQuery 插件的设计模式如下所示。

是否有任何理由为插件中的方法创建命名空间?具体来说,我对var privateMethods的使用如下所示?

(function($){
    var privateMethods={};
    privateMethods.method1=function(){alert('privateMethods1');};
    privateMethods.method2=function(){alert('privateMethods2');};
    privateMethods.method3=function(){alert('privateMethods3');};

    var privateMethod1=function(){alert('privateMethods1');};
    var privateMethod2=function(){alert('privateMethods2');};
    var privateMethod3=function(){alert('privateMethods3');};

    function privateFunction1(){
        //Consider using this approach if there is significant script
        alert('privateFunction1');
    }

    var defaults = {    //private, right?
        foo: 'bar'
    };

    var methods = {
        init : function (options) {
            var settings = $.extend({}, defaults, options);
            return this.each(function () {
                //do whatever
            });
        },
        destroy : function () {
            return this.each(function () {});
        },
        otherPublicMethod : function() {
            return $(this).each(function(){
                //do whatever
            })
        }
    };

    $.fn.myPlugin = 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.myPlugin');
        }    
    };
    }(jQuery)
);

【问题讨论】:

  • 是的,如果您希望第 3 方开发人员能够扩展您的插件以满足他们的特殊用例需求。我将使该名称空间可用,以便可以根据需要对其进行扩展/覆盖。以$.fn.myPlugin.privateMethods = {} 为例。
  • @KevinB 除了我为privateMethods 显示的内容之外,我还需要做什么才能使其可用吗?
  • 是的,因为目前唯一覆盖/扩展它的方法是直接编辑 js。 $.fn.myPlugin._ = privateMethods 最后就足够了。 methods 也可以这样做。
  • @KevinB。谢谢,这是有道理的。我是否也想做var privateMethods = privateMethods || {}; 之类的事情,或者就像我展示的那样?另外,我看到您使用_ 作为名称。然后在从插件中调用任何私有方法时,我使用_ 作为命名空间?
  • 不,插件内部没有任何改变,除了添加那一行。

标签: javascript jquery jquery-plugins namespaces


【解决方案1】:

关于插件范围之外的方法的可见性,两者之间没有区别

  • privateMethods.method
  • privateMethod1 = function(){}
  • function privateFunction(){}

另一方面,命名空间没有任何严重的缺点,除了您的 jQuery 插件将具有稍大的尺寸(通过迷你和丑化您的代码很容易缓解)。可能的优势是:

  • 通过将方法分成命名空间组来为代码引入逻辑结构
  • 在命名空间周围使用众所周知的 Javascript 模式,使您的代码具有可读性和可维护性,例如:http://addyosmani.com/blog/essential-js-namespacing/
  • 封装。与具有大量代码库的插件相关

总结:总的来说,我会随时选择使用命名空间。

【讨论】:

    猜你喜欢
    • 2014-07-20
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2012-03-02
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多