jQuery创建自己的插件(自定义插件)的方法

2020-05-17 06:27:09易采站长站整理


这种私有方法问题的解决方案称为 Closure,它可以有效地从外部调用关闭整个插件代码,附加到 jQuery 对象的除外(那些是公共方法)。通过这种设计,您可以将任何代码放入插件中,不用担心被外部脚本调用。通过将插件方法附加到 jQuery 对象,您可以有效地将它们变为公共方法,而让其他的函数/类私有化。清单 6 展示了实现该操作所需的代码。



清单 6. 私有化函数


// this code creates the Closure structure
(function(jQuery) {

 


// this function is “private”
function formatCodes(locale) {
// plug-in specific code here
}; // don’t forget the semi-colon


// this method is “public” because it’s attached to the jQuery object
jQuery.fn.format = function(options) {


var options = jQuery.extend( {


format: “#,###.00”,
locale: “us”


},options);


return this.each(function(){
var text = new String(jQuery(this).text());
if (jQuery(this).is(“:input”))
text = new String(jQuery(this).val());


// you can call the private function like any other function
var formatData = formatCodes(options.locale.toLowerCase());


// plug-in-specific code here
});
}; // don’t forget the semi-colon to close the method


// this code ends the Closure structure
})(jQuery);


 



调优 #2 – 让插件的默认值可覆盖


调优插件的最后一步是让它可以覆盖默认值。毕竟,如果德国的开发人员下载了该插件,而且了解他的所有 web 应用程序用户希望使用德文版本,那么您应该让他能够使用一行代码修改默认语言环境,而不是要他在每个方法调用中都修改一遍。这样您的插件才会非常方便,因为一个 web 应用程序不太可能使用不同的国际化格式向用户展示数字。您在网页上看一下就知道,所有数字都是使用同一个语言环境的格式。


该步骤要求您修改某处代码,因此您将看到让插件最为耀眼的一步。


清单 7. 覆盖默认值





 


jQuery.fn.format = function(options) {
// Change how you load your options in to take advantage of your overridable defaults
// You change how your extend() function works, because the defaults
// are globally defined, rather than within the method. If you didn’t use the
// {} as the first argument, you’d copy the options passed in over the defaults, which is
// undesirable. This {} creates a new temporary object to store the options
// You can simply call the defaults as an object within your plug-in
var options = jQuery.extend({},jQuery.fn.format.defaults, options);