在命名空间的jQuery插件中跨方法共享设置

我正在编写一个插件,并遵循jQuery文档的推荐做法http://docs.jquery.com/Plugins/Authoring,当涉及到命名空间和多种方法时。

我的init()负责使用$ .extend()合并默认和自定义设置但是我无法弄清楚如何在init()方法之外使这些选项可用。 假设使用调用并初始化我的插件

$("a").myplugin({debug:false}); 

我怎样才能在以后调用时引用debug属性

 $("a").myplugin("someMethod")? 

一个粗略的例子是:

  (function( $ ){ var methods = { init: function(customSettings) { var options = { debug: true } return this.each(function () { if (customSettings) { $.extend(options, customSettings); } }); }, someMethod: function() { if(options.debug) { // <-- How can I access options here? // do something } } } })( jQuery ); $.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.tbwaga'); } }; 

我没有看你的插件模板,但我想分享这个jQuery插件格式 …它在jQuery的存储数据中添加了对DOM对象的反向引用。 这使得即使从插件闭包之外也很容易访问插件函数和/或变量。

这是一篇更详细地描述插件结构的post 。

因此,要访问插件中的函数,只需使用数据对象:

 $('a').data('myplugin').function_name(); 

甚至从插件设置中获取变量

 var height = $('a').data('myplugin').options.height; 

但要回答你的问题,要使你的选项可用于闭包内的其他函数,只需在init函数之外定义选项变量:

 (function( $ ){ var options, methods = { init: function(customSettings) { options = { debug: true } 

像fudgy写的那样,您可以考虑在init方法之外设置默认值。 我尝试了同样的教程,并提出了以下代码组合设置和方法,但我遇到了一些其他的缺点。

  (function( $ ){ var config, methods = { init: function(customSettings) { var config = { debug: true } return this.each(function () { if (customSettings) { $.extend(config, customSettings); } }); }, someMethod: function(arg) { if(options.debug) { // do something alert('debug ' + arg); } else { alert('no debug' + arg); } } } $.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 ); 

但是当你打电话时:

 $('p.one').myplugin({ 'debug' : 'false' }); 

对于第二段,遗憾的是,调试仍然是错误的。

 $('p.two').myplugin('someMethod', 'hmm!'); 

我首先需要再次用’true’初始化段落以便能够调试它。

 $('p.two').myplugin({ 'debug' : 'true' }); $('p.two').myplugin('someMethod', 'hmm!'); 

我是否在教程中监督某些内容?