【发布时间】: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