之前一直有开发jquery插件的冲动,所以一直想学习如何进行插件开发,最近一个项目需要使用图片上传组件及自动无限下拉组件,百度地图组件,所以趁着这次我就把他们全部插件化了,但是在使用过程中,有一些基本的问题没有弄清楚,走了一些弯路,所以这次也总结一下:
jquery插件开发的基本格式
jquery插件开发的作用域
jquery插件开发的参数传递
jquery插件开发的方法的调用
插件开发基本格式
jquery的插件开发有两种,一种是静态方法,一种是动态的;
静态的调用方式大致是这样的:
$.dialog("你好,这是一个弹出框");
动态的调用方法大致是:
$('#helloworld').dialog('你好,这是一个弹出框!');
可以看出,他们的所在的命名空间不同,一个不依赖dom对象,一个依赖dom对象;
第一种方式,利用jquery的extend方法:
$.extend({
hello: function() {alert("hello");}
});
第二种方式,利用jquery的原型:$.fn.extend(target)
//例如:
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
如果要深入理解的话,可以参见:
http://blogs.aboutit.cn/jq_1_8_3/jQuery.fn.extend.html
http://blogs.aboutit.cn/jq_1_8_3/jQuery.extend_object.html
如果不需要绑定到dom我更倾向于第一种方式,如弹出框,弹出提示等等。
如果需要绑定的话,我一般使用下面格式:
;//加分号是为了防止压缩的时候冲突。
(function($) {
//插件所有方法集合
var l_methods = {
select_dom:function(_value,settings){
},
create_select_dom : function(data, settings,_value_obj) {
},
ajaxData : function(pid,_value_obj) {
},
init : function(options) {
var default_data = [];
return this.each(function() {
// Create a reference to the jQuery DOM object
var $this = $(this);
// Setup the default settings
var settings = $.extend({
id : $this.attr('id'), // The ID of the DOM object
value_id : $this.attr('value-id'),
url : 'admin/region/list_json',
data : default_data,
keyName : 'id',
valueName : 'name'
}, options);
//调用插件方法。。。
// ajax 请求数据
$("#"+$this.attr("id")).link_select('ajaxData', 0);
});
}
};
//插件名称定义及方法调用
$.fn.pluginName = function(method) {
if (l_methods[method]) {
return l_methods[method].apply(this, Array.prototype.slice.call(
arguments, 1));
} else if (typeof method === 'object' || !method) {
return l_methods.init.apply(this, arguments);
} else {
$.error('The method ' + method + ' does not exist in $.linkselect');
}
};
})($);
当然,上面的格式适用于我自己;可能并不是适用于你,采用这种格式,就把一些方法暴露出去了。
jquery插件开发的作用域
下面来说说作用域,在来看看,我们前面的格式:
(function ($) {
})(jQuery);
基本上是这个样的格式,这个大括号里面定义的变量,方法的作用域都只是在里面。
但是有个问题:
方法集合里面我们一般这么写:
createPrev:function(all_pic_container,$obj,_value_ids_array){
$this=$(this);
}
注意里面的this,this一般指当前对象,这个方法里面指的是什么?个人理解就是调用此方法的dom对象啦,所以,你要调用这个方法的时候,请用$('#xxxx').pluginName('方法名称');这样调用。
jquery插件开发的参数传递
插件开发过程中,肯定要穿参数,
在方法暴露出去的时候,大家可以看到,参数已经传递到方法里面去了:
$.fn.link_select = function(method) {
if (l_methods[method]) {//传递参数
return l_methods[method].apply(this, Array.prototype.slice.call(
arguments, 1));
} else if (typeof method === 'object' || !method) {
return l_methods.init.apply(this, arguments);
} else {
$.error('The method ' + method + ' does not exist in $.linkselect');
}
};
还有一种使用比较广泛的是:jquery的data函数:
$('#XXX').data("settings",settings);
具体参考:
http://blogs.aboutit.cn/jq_1_8_3/data.html
jquery插件开发的方法的调用
如果是插件专属的方法,可以写在插件内部任何方法,在使用插件的时候都会生效,如:
;
(function($) {
/**
* 依赖json.js
*/
function getJsonValue($container) {
}
xxxxxx插件其他函数
});
还有一种就是上面所说的调用方法啦:
把方法暴露出去:
return l_methods[method].apply(this, Array.prototype.slice.call(arguments, 1));