0
我最喜歡的設計模式來創建一個jQuery插件如下所示。在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)
);
是的,如果你希望第三方開發者能夠擴展你的插件以適應他們的需求,那麼他們有一個特殊的用例。我會使該名稱空間可用,以便可以根據需要對其進行擴展/重寫。例如''。$ .fn.myPlugin.privateMethods = {}'。 –
@KevinB我需要做什麼比我爲'privateMethods'顯示使其可用嗎? – user1032531
是的,因爲目前覆蓋/擴展它的唯一方法是直接編輯js。最後'$ .fn.myPlugin._ = privateMethods'就足夠了。 ''方法'可以做同樣的事情。 –