首頁  >  文章  >  php教程  >  jQuery 外掛程式封裝的方法

jQuery 外掛程式封裝的方法

高洛峰
高洛峰原創
2016-12-06 15:52:011209瀏覽

擴充jQuery外掛和方法的作用是非常強大的,它可以節省大量開發時間。這篇文章將概述jQuery插件開發的基本知識,最佳做法和常見的陷阱。

一、入門

編寫一個jQuery外掛程式開始於給jQuery.fn加入新的功能屬性,此處新增的物件屬性的名稱就是你外掛程式的名稱:

. 程式碼如下: 

jQuery.fn.myPlugin = function(){
//你自己的插件代码
};

   

. 程式碼如下: 

(function ($) {
$.fn.myPlugin = function () {
//你自己的插件代码
};
})(jQuery);

    使用者非常喜歡的符號哪裡去了?它仍然存在,但是,為了避免和其他JavaScript庫衝突,我們最好將jQuery傳遞給一個自我執行的封閉程序,jQuery在此程序中映射為符號,這樣可以避免$號被其他庫覆蓋。

. 程式碼如下:

(function ($) {
$.fn.myPlugin = function () {
//此处没有必要将this包在$号中如$(this),因为this已经是一个jQuery对象。
//$(this)等同于 $($('#element'));
this.fadeIn('normal', function () {
//此处callback函数中this关键字代表一个DOM元素
});
};
})(jQuery);
$('#element').myPlugin();

   

在這個封閉程式中,我們可以無限的使用$符號來表示jQuery函數。

二、環境

現在,我們可以開始寫實際的外掛程式碼。 但是,在這之前,我們必須要對插件所處的環境有個概念。 在插件的範圍裡, this關鍵字代表了這個插件將要執行的jQuery對象, 這裡容易產生一個普遍的誤區,因為在其他包含callback的jQuery函數中,this關鍵字代表了原生的DOM元素。這常常會導致開發者誤將this關鍵字無謂的包在jQuery中,如下所示。

. 程式碼如下:

(function ($) {
$.fn.maxHeight = function () {
var max = 0;
this.each(function () {
max = Math.max(max, $(this).height());
});
return max;
};
})(jQuery);
var tallest = $('div').maxHeight(); //返回高度最大的div元素的高度
   
这是一个简单的插件,利用.height()返回页面中高度最大的div元素的高度。

   

三、基礎知識

現在,我們理解了jQuery插件的基礎知識,讓我們寫一個插件,做一些事情。

. 程式碼如下:

(function ($) {
$.fn.lockDimensions = function (type) {
return this.each(function () {
var $this = $(this);
if (!type || type == 'width') {
$this.width($this.width());
}
if (!type || type == 'height') {
$this.height($this.height());
}
});
};
})(jQuery);
$('div').lockDimensions('width').CSS('color', 'red');

四、維護Chainability

很多時候,一個插件的意圖僅僅是以某種方式修改收集的元素,並把它們傳遞給鏈中的下一個方法。 這是jQuery的設計之美,也是jQuery如此受歡迎的原因之一。 因此,要保持一個插件的chainability,你必須確保你的插件回到this關鍵字。

. 程式碼如下:

(function ($) {
$.fn.tooltip = function (options) {
//创建一些默认值,拓展任何被提供的选项
var settings = $.extend({
'location': 'top',
'background-color': 'blue'
}, options);
return this.each(function () {
// Tooltip插件代码
});
};
})(jQuery);
$('div').tooltip({
'location': 'left'
});

   

由於插件返回this關鍵字,它保持了chainability,這樣jQuery收集的元素可以繼續被jQuery方法如.css控制。 因此,如果你的外掛不回傳固有的價值,你應該總是在其作用範圍內回傳this關鍵字。 此外,你可能會推斷出,傳遞給插件的參數將會在插件的作用範圍內傳遞。 因此,在前面的例子,字串'width'變成了插件的類型參數。

五、預設值和選項

對於比較複雜的和提供了許多選項可定制的的插件,最好有一個當插件被調用的時候可以被拓展的默認設置(通過使用$.extend)。 因此,相對於呼叫一個有大量參數的插件,你可以呼叫一個物件參數,包含你了你想覆寫的設定。

. 程式碼如下:

{
'location': 'left',
'background-color': 'blue'
}

   

在這個例子中,呼叫tooltip插件時覆寫了預設設定中的location選項,background-color選項保持預設值,所以最終被呼叫的設定值為:

. 程式碼如下:

(function ($) {
$.fn.tooltip = function (options) {
// this
};
$.fn.tooltipShow = function () {
// is
};
$.fn.tooltipHide = function () {
// bad
};
$.fn.tooltipUpdate = function (content) {
// !!!
};
})(jQuery);

   

這是一個很靈活的方式,提供一個高度可設定的插件,而無需開發人員定義所有可用的選項。

六、命名空間

正確命名空間你的插件是插件開發的一個非常重要的一部分。 正確的命名空間,可以確保你的外掛將有一個非常低的機會被其他外掛程式或同一頁上的其他程式碼覆蓋。 命名空間也使得你的生活作為一個插件開發人員更容易,因為它可以幫助你更好地追蹤你的方法,事件和數據。

七、插件方法

在任何情況下,一個單獨的插件不應該在jQuery.fnjQuery.fn物件裡有多個命名空間。

. 代碼如下:

(function ($) {
var methods = {
init: function (options) {
// this
},
show: function () {
// is
},
hide: function () {
// good
},
update: function (content) {
// !!!
}
};
$.fn.tooltip = function (method) {
// 方法调用
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method' + method + 'does not exist on jQuery.tooltip');
}
};
})(jQuery);
//调用init方法
$('div').tooltip();
//调用init方法
$('div').tooltip({
foo: 'bar'
});
// 调用hide方法
$(‘div').tooltip(‘hide');
//调用Update方法
$(‘div').tooltip(‘update', ‘This is the new tooltip content!');

   

這是不被鼓勵的,因為它.fn使.fn命名空間混亂。 為了解決這個問題,你應該收集物件文字中的所有插件的方法,透過傳遞該方法的字串名稱給插件以呼叫它們。

. 程式碼如下:

(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
$(window).bind('resize.tooltip', methods.reposition);
});
},
destroy: function () {
return this.each(function () {
$(window).unbind('.tooltip');
})
},
reposition: function () {
//...
},
show: function () {
//...
},
hide: function () {
//...
},
update: function (content) {
//...
}
};
$.fn.tooltip = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.tooltip');
}
};
})(jQuery);
$('#fun').tooltip();
//一段时间之后… …
$(‘#fun').tooltip(‘destroy');

   

這種類型的插件架構允許您封裝所有的方法在父包中,透過傳遞該方法的字串名稱和額外的此方法需要的參數來呼叫它們。 這種方法的封裝和架構類型是jQuery插件社群的標準,它被無數的插件在使用,包括jQueryUI中的插件和widgets。

八、事件

一個鮮為人知bind方法的功能即允許綁定事件命名空間。 如果你的插件綁定一個事件,一個很好的做法是賦予此事件命名空間。 透過這種方式,當你在解除綁定的時候不會幹擾其他可能已經綁定的相同類型事件。 你可以透過追加命名空間到你需要綁定的事件通過 ‘.'。 


. 代碼如下:

(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('tooltip'),
tooltip = $(&#39;<div />&#39;, {
text: $this.attr(&#39;title&#39;)
});
// If the plugin hasn&#39;t been initialized yet
if (!data) {
/*
Do more setup stuff here
*/
$(this).data(&#39;tooltip&#39;, {
target: $this,
tooltip: tooltip
});
}
});
},
destroy: function () {
return this.each(function () {
var $this = $(this),
data = $this.data(&#39;tooltip&#39;);
// Namespacing FTW
$(window).unbind(&#39;.tooltip&#39;);
data.tooltip.remove();
$this.removeData(&#39;tooltip&#39;);
})
},
reposition: function () {
// ...
},
show: function () {
// ...
},
hide: function () {
// ...
},
update: function (content) {
// ...
}
};
$.fn.tooltip = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === &#39;object&#39; || !method) {
return methods.init.apply(this, arguments);
} else {
$.error(&#39;Method &#39; + method + &#39; does not exist on jQuery.tooltip&#39;);
}
};
})(jQuery);

   

在这个例子中,当tooltip通过init方法初始化时,它将reposition方法绑定到resize事件并给reposition非那方法赋予命名空间通过追加.tooltip。 稍后, 当开发人员需要销毁tooltip的时候,我们可以同时解除其中reposition方法和resize事件的绑定,通过传递reposition的命名空间给插件。 这使我们能够安全地解除事件的绑定并不会影响到此插件之外的绑定。

九、数据

通常在插件开发的时候,你可能需要记录或者检查你的插件是否已经被初始化给了一个元素。 使用jQuery的data方法是一个很好的基于元素的记录变量的途径。尽管如此,相对于记录大量的不同名字的分离的data, 使用一个单独的对象保存所有变量,并通过一个单独的命名空间读取这个对象不失为一个更好的方法。

. 代码如下:

(function ($) {
var methods = {
init: function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data(&#39;tooltip&#39;),
tooltip = $(&#39;<div />&#39;, {
text: $this.attr(&#39;title&#39;)
});
// If the plugin hasn&#39;t been initialized yet
if (!data) {
/*
Do more setup stuff here
*/
$(this).data(&#39;tooltip&#39;, {
target: $this,
tooltip: tooltip
});
}
});
},
destroy: function () {
return this.each(function () {
var $this = $(this),
data = $this.data(&#39;tooltip&#39;);
// Namespacing FTW
$(window).unbind(&#39;.tooltip&#39;);
data.tooltip.remove();
$this.removeData(&#39;tooltip&#39;);
})
},
reposition: function () {
// ...
},
show: function () {
// ...
},
hide: function () {
// ...
},
update: function (content) {
// ...
}
};
$.fn.tooltip = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === &#39;object&#39; || !method) {
return methods.init.apply(this, arguments);
} else {
$.error(&#39;Method &#39; + method + &#39; does not exist on jQuery.tooltip&#39;);
}
};
})(jQuery);

   

将数据通过命名空间封装在一个对象中,可以更容易的从一个集中的位置读取所有插件的属性。

十、总结和最佳做法

编写jQuery插件允许你做出库,将最有用的功能集成到可重用的代码,可以节省开发者的时间,使开发更高效。 开发jQuery插件时,要牢记:

1.始终包裹在一个封闭的插件:

. 代码如下:

(function($) {
/* plugin goes here */
})(jQuery);

   

2.不要冗余包裹this关键字在插件的功能范围内

3.除非插件返回特定值,否则总是返回this关键字来维持chainability 。

4.传递一个可拓展的默认对象参数而不是大量的参数给插件。

5.不要在一个插件中多次命名不同方法。

3.始终命名空间的方法,事件和数据。

最后加一个自己写的放大镜的插件`

(function($){$.fn.Fdj=function(){
$(&#39;#smallImg&#39;).on(&#39;mouseover&#39;, function() {
$(&#39;#slider&#39;).show();
})
$(&#39;#smallImg&#39;).on(&#39;mouseout&#39;, function() {
$(&#39;#slider&#39;).hide();
})
$(&#39;#smallImg&#39;).on(&#39;mousemove&#39;, function(e) {
var x = e.clientX - $(&#39;#slider&#39;).width() / 2;
var y = e.clientY - $(&#39;#slider&#39;).height() / 2;
if(x <= 0) {
x = 0
}
if(x > $(&#39;#smallImg&#39;).width() - $(&#39;#slider&#39;).width()) {
x = $(&#39;#smallImg&#39;).width() - $(&#39;#slider&#39;).width();
}
if(y <= 0) {
y = 0
}
if(y > $(&#39;#smallImg&#39;).height() - $(&#39;#slider&#39;).height()) {
y = $(&#39;#smallImg&#39;).height() - $(&#39;#slider&#39;).height();
}
$(&#39;#slider&#39;).css({
&#39;left&#39;: x,
&#39;top&#39;: y
})
var X=x/$(&#39;#smallImg&#39;).width()*800
var Y=y/$(&#39;#smallImg&#39;).height()*800
$(&#39;#img&#39;).css({
left:-X,
top:-Y
})
})
}
})(jQuery)

   


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn