首先,正如 Spycho 所说,始终将插件包装在
(function( $ ){
$.fn.PluginName = function() {
// plugin goes here
};
})( jQuery );
避免与使用美元符号的其他库发生冲突。
其次,如果您扩展jQuery.fn 对象,则使用$("#myDiv") 之类的名称调用的选择将作为this 传递给插件。这样您就不必像以前那样将选择作为参数传递给插件。
第三,你做对了,他们建议你将选项作为一个对象而不是单个参数传递给插件,这样你就可以轻松地拥有和覆盖默认值:
(function( $ ){
$.fn.PluginName = function(options) {
var settings = { myOption: 1 };
if (options) {
$.extend( settings, options );
}
// plugin goes here
};
})( jQuery );
第四,您创建 _privateMethod 的方式实际上并没有将其设为私有,为此您可以遵循 jQuery 在 plugin authoring guidelines 中建议的模式
(function( $ ){
var methods = {
publicMethod: function(options) {
var settings = { myOption: 1 };
if (options) {
$.extend( settings, options );
}
},
_privateMethod: function() {}
}
$.fn.PluginName = function(methodName, options) {
// use some logic to control what methods are public
if (methodName == "publicMethod") {
return publicMethod.apply(this, Array.prototype.slice.call( arguments, 1 ));
}
};
})( jQuery );
这使用了apply 和call,它们是用于设置函数调用范围的花哨的内置函数方法,请参阅MDN reference 以了解那里发生了什么。通过这种方式,您实际上可以控制哪些方法是公共的还是私有的。
编辑: 最后,如果你想完全维护 jQuery 的流畅界面,并且让你的插件都接受$() 传递的选择并将其传递,换句话说,是可链接的,你的方法需要返回给定对象的集合:
(function( $ ){
var methods = {
publicMethod: function(options) {
var settings = { myOption: 1 };
if (options) {
$.extend( settings, options );
}
return this.each(function() {
this.value = (this.value * 1) + settings.myOption;
});
},
_privateMethod: function() {}
}
$.fn.PluginName = function(methodName, options) {
// use some logic to control what methods are public
if (methodName == "publicMethod") {
return methods.publicMethod.apply(this, Array.prototype.slice.call( arguments, 1 ));
}
};
})( jQuery );
查看jsFiddle 了解最终工作示例。