编写一个jQuery插件开始于给jQuery.fn加入新的功能属性,此处添加的对象属性的名称就是你插件的名称:
- 1 jQuery.fn.myPlugin = function(){
- 2 //你自己的插件代码
- 3 };
为什么不用$符号呢?为了避免和其他JavaScript库冲突,我们最好将jQuery传递给一个自我执行的封闭程序,jQuery在此程序中映射为符号,这样可以避免$号被其他库覆写。
- (function ($) {
- $.fn.myPlugin = function () {
- //你自己的插件代码
- };
- })(jQuery);
在这个封闭程序中,我们可以无限制的使用$符号来表示jQuery函数。
现在,我们可以开始编写实际的插件代码。 但是,在这之前,我们必须得对插件所处的环境有个概念。 在插件的范围里, this关键字代表了这个插件将要执行的jQuery对象, 这里容易产生一个普遍的误区,因为在其他包含callback的jQuery函数中,this关键字代表了原生的DOM元素。这常常会导致开发者误将this关键字无谓的包在jQuery中,如下所示。
- (function ($) {
- $.fn.myPlugin = function () {
- //此处没有必要将this包在$号中如$(this),因为this已经是一个jQuery对象。
- //$(this)等同于 $($('#element'));
- this.fadeIn('normal', function () {
- //此处callback函数中this关键字代表一个DOM元素
- });
- };
- })(jQuery);
- $('#element').myPlugin();
现在,我们做一个利用.height()返回页面中高度最大的div元素的高度。
- (function ($) {
- $.fn.maxHeight = function () {
- var max = 0;
- this.each(function () {
- max = Math.max(max, $(this).height());
- });
- return max;
- };
- })(jQuery);
- var tallest = $('div').maxHeight(); //返回高度最大的p元素的高度
维护Chainability
很多时候,一个插件的意图仅仅是以某种方式修改收集的元素,并把它们传递给链中的下一个方法。 这是jQuery的设计之美,是jQuery如此受欢迎的原因之一。 因此,要保持一个插件的chainability,你必须确保你的插件返回this关键字。
- 1 (function ($) {
- 2 $.fn.lockDimensions = function (type) {
- 3 return this.each(function () {
- 4 var $this = $(this);
- 5 if (!type || type == 'width') {
- 6 $this.width($this.width());
- 7 }
- 8 if (!type || type == 'height') {
- 9 $this.height($this.height());
- 10 }
- 11 });
- 12 };
- 13 })(jQuery);
- 14 $('p').lockDimensions('width').CSS('color', 'red');
由于插件返回this关键字,它保持了chainability,这样jQuery收集的元素可以继续被jQuery方法如.css控制。 因此,如果你的插件不返回固有的价值,你应该总是在其作用范围内返回this关键字。 此外,你可能会推断出,传递给插件的参数将会在插件的作用范围内被传递。 因此,在前面的例子,字符串'width'变成了插件的类型参数。
默认值和选项
对于比较复杂的和提供了许多选项可定制的的插件,最好有一个当插件被调用的时候可以被拓展的默认设置(通过使用$.extend)。 因此,相对于调用一个有大量参数的插件,你可以调用一个对象参数,包含你了你想覆写的设置。
- (function ($) {
- $.fn.tooltip = function (options) {
- //创建一些默认值,拓展任何被提供的选项
- var settings = $.extend({
- 'location': 'top',
- 'background-color': 'blue'
- }, options);
- return this.each(function () {
- // Tooltip插件代码
- });
- };
- })(jQuery);
- $('p').tooltip({
- 'location': 'left'
- });
在这个例子中,调用tooltip插件时覆写了默认设置中的location选项,background-color选项保持默认值,所以最终被调用的设定值为:
- {
- 'location': 'left',
- 'background-color': 'blue',
- }
命名空间
正确命名空间你的插件是插件开发的一个非常重要的一部分。 正确的命名空间,可以保证你的插件将有一个非常低的机会被其他插件或同一页上的其他代码覆盖,也可以可以帮助你更好地跟踪你的方法,事件和数据。
插件方法
在任何情况下,一个单独的插件不应该在jQuery.fnjQuery.fn对象里有多个命名空间。
- 1 (function ($) {
- 2 $.fn.tooltip = function (options) {
- 3 // this
- 4 };
- 5 $.fn.tooltipShow = function () {
- 6 // is
- 7 };
- 8 $.fn.tooltipHide = function () {
- 9 // bad
- 10 };
- 11 $.fn.tooltipUpdate = function (content) {
- 12 // !!!
- 13 };
- 14 })(jQuery);
这是不被鼓励的,因为它.fn使.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方法
- $('p').tooltip();
- //调用init方法
- $('p').tooltip({
- foo: 'bar'
- });
- // 调用hide方法
- $('p').tooltip('hide');
- //调用Update方法
- $('p').tooltip('update', 'This is the new tooltip content!');
这种类型的插件架构允许您封装所有的方法在父包中,通过传递该方法的字符串名称和额外的此方法需要的参数来调用它们。 这种方法的封装和架构类型是jQuery插件社区的标准,它被无数的插件在使用,包括jQueryUI中的插件和widgets。
事件
一个鲜为人知bind方法的功能即允许绑定事件命名空间。 如果你的插件绑定一个事件,一个很好的做法是赋予此事件命名空间。 通过这种方式,当你在解除绑定的时候不会干扰其他可能已经绑定的同一类型事件。 你可以通过追加命名空间到你需要绑定的的事件通过 ‘.'。
- (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');
在这个例子中,当tooltip通过init方法初始化时,它将reposition方法绑定到resize事件并给reposition非那方法赋予命名空间通过追加.tooltip。 稍后, 当开发人员需要销毁tooltip的时候,我们可以同时解除其中reposition方法和resize事件的绑定,通过传递reposition的命名空间给插件。 这使我们能够安全地解除事件的绑定并不会影响到此插件之外的绑定。
资料来源于http://www.php.cn/js-tutorial-393917.html