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

调优插件的最后一步是让它可以覆盖默认值。毕竟,如果德国的开发人员下载了该插件,而且了解他的所有 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);

return this.each(function(){

// rest of the plug-in code here

// define the defaults here as an object in the plug-in
jQuery.fn.format.defaults = {
format: "#,###.00",
locale: "us"
}; // don't forget the semi-colon

 

这是创建插件的最后一个步骤!这样您就有了一个不错的插件,可以进行最后的测试了。清单 8 展示了您可以放入本文的完整插件,以便您查看这些部分是如何变为一个整体的。此外还包含了 parse() 函数,到目前为止我还没有讨论过该函数,但是它包含在插件中(我没有详细介绍插件处理格式化的部分,因为它们不在本文讨论之列。样例中包含了该部分,插件本身当然也有)。


清单 8. NumberFormatter 插件

(function(jQuery) {

function FormatData(valid, dec, group, neg) {
this.valid = valid;
this.dec = dec;
this.group = group;
this.neg = neg;
};

function formatCodes(locale) {
// format logic goes here
return new FormatData(valid, dec, group, neg);
};

jQuery.fn.parse = function(options) {

var options = jQuery.extend({},jQuery.fn.parse.defaults, options);

var formatData = formatCodes(options.locale.toLowerCase());

var valid = formatData.valid;
var dec = formatData.dec;
var group = formatData.group;
var neg = formatData.neg;

var array = [];
this.each(function(){

var text = new String(jQuery(this).text());
if (jQuery(this).is(":input"))
text = new String(jQuery(this).val());


// now we need to convert it into a number
var number = new Number(text.replace(group,'').replace(dec,".").replace(neg,"-"));
array.push(number);
});

return array;
};

jQuery.fn.format = function(options) {

var options = jQuery.extend({},jQuery.fn.format.defaults, options);

var formatData = formatCodes(options.locale.toLowerCase());

var valid = formatData.valid;
var dec = formatData.dec;
var group = formatData.group;
var neg = formatData.neg;

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

// formatting logic goes here

if (jQuery(this).is(":input"))
jQuery(this).val(returnString);
else
jQuery(this).text(returnString);
});
};

jQuery.fn.parse.defaults = {
locale: "us"
};

jQuery.fn.format.defaults = {
format: "#,###.00",
locale: "us"
};

})(jQuery);

 

测试插件

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdxxyf.html