jQuery插件編寫規範

第一種方法:

在不少基於jQuery或基於Zepto的插件中,在當即函數執行前面會加上";"這個符號。javascript

這是爲了防止前面的其餘插件沒有正常關閉。java

在當即執行函數執行時,會通常會傳入jQuery,window等。舉個例子:函數

;(function($,window,undefined){
	//.....
})(jQuery,window)

window傳遞進來做爲局部變量存在,而非全局變量,這樣能夠加快解析流程,以及影響最小化。ui

undefined沒有傳進來,以即可以確保此undefined是真正的undefined。由於ECMAScript3裏的undefined是能夠修改的,ECMAScript5不能夠修改。this

下面是自定義jQuery插件的規範:prototype

;(function($,window,undefined){
	var pluginName = "chaojidan",
		defaults = {
			name:"dandan"
		};
	function Plugin(element, options){
		this.element = element;
		this.options = $.extend( {} , defaults,options );
		this._name = pluginName;
		this._defaults = defaults;
		this.init();
	}
	Plugin.prototype.init = function(){
		//初始化插件
	};
	$.fn[pluginName] = function(options){     //真正的插件包裝,防止出現多個實例
		return this.each(function(){
			if(!$.data(this,"plugin_"+pluginName)){
				$.data(this,"plugin_"+pluginName, new Plugin(this, options));
			}
		});
	}

})(jQuery,window)

調用此插件:插件

$("#elem").chaojidan({name:"xiaoxiao"});  對象

第二種方法:

;(function($,window,undefined){
	var myObject = {
		init : function(options, elem){
			this.options = $.extend({}, this.options, options);
			this.elem = elem;
			this.$elem = $(elem);
			this._build();
			return this;
		},
		options:{
			name:"dandan"
		},
		_build:function(){

		},
		myMethod:function(){

		}
	};
	if(typeof Object.create != "function"){
		Object.create = function(o){
			function F(){}
			F.prototype = o;
			return new F();
		}
	}
	$.plugin = function(name, object){
		$.fn[name] = function(options){
			return this.each(function(){
				if(!$.data(this,name)){
					$.data(this,name,Object.create(object).init(options,this))
				}
			});
		}
	}
    $.plugin("chaojidan",myObject);
})(jQuery,window);

調用方式:blog

$("#elem").chaojidan({name:"xiaoxiao"}); ip

對於上面的兩種方法,咱們定義插件時,都傳遞了帶有默認值的對象字面量給$.extend()。然而,若是咱們想自定義此默認值的對象字面量,也就是說,用戶能夠重寫此默認對象字面量,那麼咱們該如何來寫呢?

其實很是簡單,咱們只要把此默認對象字面量這樣賦值就好了。

$.fn.pluginName.options = {
  name:"dandan"
}

這樣,用戶可以重寫全局默認配置,達到插件構造的靈活性。

 

 

 

 

加油! 

相關文章
相關標籤/搜索