我尝试制作我的第一个 jquery 插件(灯箱)。它按照我想要的方式在单个元素上工作,但如果我使用多个元素,它会覆盖我的选项。
这是我当前的代码。由于布局的原因,它似乎不适用于 jsFiddle。
您可以在此处下载带有工作(失败)示例的代码:
http://frumbert.org/files/frumbox.zip
我可以看到,当我绑定(bind)到第二个对象时,我以某种方式覆盖了默认对象中的选项,但不知道我做错了什么。我尝试移动点击绑定(bind)的位置,但无法使其工作。
最佳答案
$this 在最外层闭包中声明并在整个过程中使用,表示实例化 FrumBox 的最后一个元素。
就我个人而言,我不会尝试按原样修复代码。相反采用 jQuery's "Best Practices" pattern 。这是我基于给定示例的模板:
(function($){
// **********************************
// ***** Start: Private Members *****
var pluginName = 'xxxxx';
// ***** Fin: Private Members *****
// ********************************
// *********************************
// ***** Start: Public Methods *****
var methods = {
init : function(options) {
//"this" is a jquery object on which this plugin has been invoked.
return this.each(function(index){
var $this = $(this);
var data = $this.data(pluginName);
// If the plugin hasn't been initialized yet
if (!data){
var settings = {
};
if(options) { $.extend(true, settings, options); }
$this.data(pluginName, {
target : $this,
settings: settings
});
}
});
},
myMethod_1 : function(){.....},
myMethod_2 : function(){.....}
};
// ***** Fin: Public Methods *****
// *******************************
// *****************************
// ***** Start: Supervisor *****
$.fn[pluginName] = 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 in jQuery.' + pluginName );
}
};
// ***** Fin: Supervisor *****
// ***************************
})( jQuery );
注释:
- 根据需要添加更多私有(private)成员和方法。
- 公共(public)成员(方法)具有特权(他们可以访问私有(private)成员)。
- 为了保持可链接性,请务必在每个方法中采用
return this.each(function(index){...})
模式(返回特定值的方法除外)。 - 可以说,使用此模式(和其他模式)进行开发的最困难的方面是了解
this
在每个上下文中指代的内容。保持头脑清醒。 - 准备好使用 JavaScript
Function.call()
和Function.apply
方法。确保您理解它们。 - 主管乍一看很难理解,但其实没必要 修改的。这是一段很酷的代码。
- 使用
$(selector).pluginNmae()
或$(selector).pluginNmae(options)
在 DOM 元素上实例化插件,其中options
是一个对象文字“map”。 - 使用
$(selector).pluginNmae('methodName', ...) 在初始化的 DOM 元素上调用方法
- 此模式的示例可以在 selected answer here 中找到。 (包括 fiddle 的链接)。
关于jquery 插件不适用于多个元素 - 选项被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746498/