在命名空间jQuery插件中的方法之间共享设置 [英] Sharing settings across methods in namespaced jQuery plugin
问题描述
我正在编写一个插件,并遵循jQuery文档的推荐做法 http://docs.jquery.com/Plugins/Authoring 涉及命名空间和多种方法.
I'm writing a plugin and following the jQuery documentation's recommended practice http://docs.jquery.com/Plugins/Authoring when it comes to namespacing and multiple methods.
我的init()负责使用$ .extend()合并默认设置和自定义设置,但是我不知道如何使这些选项在init()方法之外可用.说该调用并使用
My init() takes care of merging default and custom settings using $.extend() however I can not figure out how to make those options available outside of the init() method. Say that call and initialize my plugin using
$("a").myplugin({debug:false});
稍后调用
$("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对象的反向引用.这样一来,即使从插件关闭的外部,也可以非常轻松地访问插件函数和/或变量.
I didn't look at your plugin template, but I wanted to share this jQuery plugin formatting... it adds a reverse reference to the DOM object in jQuery's stored data. This makes it very easy to access the plugin functions and/or variables even from outside of the plugin closure.
这是帖子,描述了插件结构更详细.
Here is a post describing the plugin structure in more detail.
因此,要访问插件中的函数,只需使用数据对象:
So to access a function inside the plugin, you simply use the data object:
$('a').data('myplugin').function_name();
甚至从插件设置中获取变量
or even get a variable from the plugin settings
var height = $('a').data('myplugin').options.height;
但是要回答您的问题,要使选项对闭包内部的其他函数可用,只需在init函数之外定义option变量:
But to answer your question, to make your options available to other functions inside the closure, just define the option variable outside of the init function:
(function( $ ){
var options, methods = {
init: function(customSettings) {
options = {
debug: true
}
这篇关于在命名空间jQuery插件中的方法之间共享设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!