我正在编写一个插件,并遵循jQuery文档的推荐做法http://docs.jquery.com/Plugins/Authoring,当涉及到命名空间和多种方法时.
我的init()负责使用$ .extend()合并默认和自定义设置但是我无法弄清楚如何在init()方法之外使这些选项可用.说使用调用并初始化我的插件
$("a").myplugin({debug:false});
Run Code Online (Sandbox Code Playgroud)
我怎样才能在以后调用时引用debug属性
$("a").myplugin("someMethod")?
Run Code Online (Sandbox Code Playgroud)
一个粗略的例子是:
(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');
}
};
Run Code Online (Sandbox Code Playgroud)
我没有看你的插件模板,但我想分享这个jQuery插件格式 ...它在jQuery的存储数据中添加了对DOM对象的反向引用.这使得即使从插件闭包之外也很容易访问插件函数和/或变量.
这是一篇更详细地描述插件结构的帖子.
因此,要访问插件中的函数,只需使用数据对象:
$('a').data('myplugin').function_name();
Run Code Online (Sandbox Code Playgroud)
甚至从插件设置中获取变量
var height = $('a').data('myplugin').options.height;
Run Code Online (Sandbox Code Playgroud)
但要回答你的问题,要使你的选项可用于闭包内的其他函数,只需在init函数之外定义选项变量:
(function( $ ){
var options, methods = {
init: function(customSettings) {
options = {
debug: true
}
Run Code Online (Sandbox Code Playgroud)