总结jQuery插件开发中的一些要点


Posted in Javascript onMay 16, 2016

基础
1、jQuery插件开发主要使用如下两个方法:
1.1、添加静态方法

jQuery.extend(object);

为扩展jQuery本身,为类添加新的方法,可以理解文添加静态方法。

$.extend({ 
addMethod : function(a, b){return a + b;}  // $.addMethod(1, 2); //return 3
});

1.2、添加成员方法

jQuery.fn.extend(object);
jQuery.fn = jQuery.prototype

给jQuery对象添加方法,对jQuery.prototype进行扩展,为jQuery类添加成员方法:

$.fn.extend({ 
  getInputText:function(){ 
    $(this).click(function(){ 
      alert($(this).val()); 
    }); 
  } 
});

$("#username").getInputText();

 

2、一个通用的框架:
以下是一个通用的框架:

(function($){ 
  $.fn.yourPluginName = function(options){ 
    //各种属性和参数 

    var options = $.extend(defaults, options); 

    this.each(function(){ 
      //插件的实现代码

    }); 
  }; 
})(jQuery);

关于

$.extend(defaults, options);

就是通过合并defaults和options来扩展defaults,实现插件默认参数的功能。

实践

1、声明插件名称:
添加一个函数到jQuery.fn(jQuery.prototype)对象,该函数的名称就是你的插件名称:

jQuery.fn.myPlugin = function() {

 // Do your awesome plugin stuff here

};

在命名不与jQuery其他函数冲突的情况,可以使用闭包的方式使用$符号:

(function( $ ) {
 $.fn.myPlugin = function() {

  // Do your awesome plugin stuff here

 };
})( jQuery );

2、插件中的上下文:
jQuery接收一个回调,该回调本身就指向了dom,直接使用this就相当于我们平时的$(this)的情况:

(function( $ ){

 $.fn.myPlugin = function() {

  // there's no need to do $(this) because
  // "this" is already a jquery object

  // $(this) would be the same as $($('#element'));

  this.fadeIn('normal', function(){

   // the this keyword is a DOM element

  });

 };
})( jQuery );
$('#element').myPlugin();

下面是一个简单的jQuery插件,实现获取所有div的最大高度:

(function( $ ){

 $.fn.maxHeight = function() {

  var max = 0;

  this.each(function() {
   max = Math.max( max, $(this).height() );
  });

  return max;
 };
})( jQuery );
var tallest = $('div').maxHeight(); // Returns the height of the tallest div

3、维护链接性:
前面的示例返回一个整数值最高的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');

因为插件返回this关键字的范围,它维护链接性,jQuery可以继续利用jQuery方法,如. css。所以,如果你的插件不返回一个内在价值,你应该总是返回this。

4、参数的传递,Defaults和Options:

(function( $ ){

 $.fn.tooltip = function( options ) { 

  // Create some defaults, extending them with any options that were provided
  var settings = $.extend( {
   'location'     : 'top',
   'background-color' : 'blue'
  }, options);

  return this.each(function() {    

   // Tooltip plugin code here

  });

 };
})( jQuery );
$('div').tooltip({
 'location' : 'left'
});

通过$.extend合并默认参数和调用者传入的参数。

5、命名空间:
正确的命名空间在插件开发中是一个非常重要的部分。正确的命名空间,可以确保你的插件将有一个很低的几率在同一个页面上被他插件或代码覆盖。

在任何情况下都不应该在一个插件的jQuery.fn对象中声称多个名称空间。

(function( $ ){

 $.fn.tooltip = function( options ) { 
  // THIS
 };
 $.fn.tooltipShow = function( ) {
  // IS
 };
 $.fn.tooltipHide = function( ) { 
  // BAD
 };
 $.fn.tooltipUpdate = function( content ) { 
  // !!! 
 };

})( jQuery );

你应该收集所有的方法到一个对象化字面,并且通过方法的字面值进行调用:

(function( $ ){

 var methods = {
  init : function( options ) { 
   // THIS 
  },
  show : function( ) {
   // IS
  },
  hide : function( ) { 
   // GOOD
  },
  update : function( content ) { 
   // !!! 
  }
 };

 $.fn.tooltip = function( method ) {

  // Method calling logic
  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 );

// calls the init method
$('div').tooltip(); 

// calls the init method
$('div').tooltip({
 foo : 'bar'
});
// calls the hide method
$('div').tooltip('hide'); 
// calls the update method
$('div').tooltip('update', 'This is the new tooltip content!');

这种类型的方法封装和体系结构在jQuery插件社区中是一个标准,它适用于无数的插件,包括jQueryUI插件和小部件。

6、Events:
Bind方法允许通过命名空间的方式绑定事件,如果你的插件绑定了事件,可以通过命名空间的方式,在解除绑定事件时,你也可以这样做,来防止影响到其他的事件。可以通过“.<namespace>” 的方式来设置绑定事件的命名空间。

(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();
// Some time later...
$('#fun').tooltip('destroy');

7、Data:
关于data方法可以参考官方的文档:http://docs.jquery.com/Data,既是在页面的元素中绑定存储数据。

这里通过编写插件,实现在页面中的每个元素都绑定一些当前的状态或者内容。

(function( $ ){

 var methods = {
   init : function( options ) {

    return this.each(function(){

     var $this = $(this),
       data = $this.data('tooltip'),
       tooltip = $('<div />', {
        text : $this.attr('title')
       });

     // If the plugin hasn't been initialized yet
     if ( ! data ) {

      /*
 Do more setup stuff here
 */

      $(this).data('tooltip', {
        target : $this,
        tooltip : tooltip
      });

     }
    });
   },
   destroy : function( ) {

    return this.each(function(){

     var $this = $(this),
       data = $this.data('tooltip');

     // Namespacing FTW
     $(window).unbind('.tooltip');
     data.tooltip.remove();
     $this.removeData('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 );
Javascript 相关文章推荐
javascript入门·动态的时钟,显示完整的一些方法,新年倒计时
Oct 01 Javascript
javascript prototype原型操作笔记
Dec 07 Javascript
JSQL  一个 web DB 的封装
May 05 Javascript
jQuery 淡出一个图像到另一个图像的实现代码
Jun 12 Javascript
jQuery简单实现中间浮窗效果
Sep 04 Javascript
基于jQuery实现Accordion手风琴自定义插件
Oct 13 Javascript
聊聊JavaScript如何实现继承及特点
Apr 07 Javascript
基于layui框架响应式布局的一些使用详解
Sep 16 Javascript
vue实现微信浏览器左上角返回按钮拦截功能
Jan 18 Javascript
Vue常用的全选/反选的示例代码
Feb 19 Javascript
小程序跳转到的H5页面再跳转回跳小程序的方法
Mar 06 Javascript
vue代码分块和懒加载非必要资源文件
Apr 11 Vue.js
JavaScript编写Chrome扩展实现与浏览器的交互及时间通知
May 16 #Javascript
动态的9*9乘法表效果的实现代码
May 16 #Javascript
Svg.js实例教程及使用手册详解(一)
May 16 #Javascript
限制只能输入数字的实现代码
May 16 #Javascript
JavaScript开发Chrome浏览器扩展程序UI的教程
May 16 #Javascript
基于javascript实现最简单的选项卡切换效果
May 16 #Javascript
JavaScript实现页面跳转的方式汇总
May 16 #Javascript
You might like
php+Mysqli利用事务处理转账问题实例
2015/02/11 PHP
thinkphp自带验证码全面解析
2016/09/18 PHP
自动更新作用
2006/10/08 Javascript
prototype 学习笔记整理
2009/07/17 Javascript
用Javascript实现Sleep暂停功能代码
2010/09/03 Javascript
情人节专属 纯js脚本1k大小的3D玫瑰效果
2012/02/11 Javascript
jquery如何通过name名称获取当前name的value值
2013/12/20 Javascript
深入探讨javascript函数式编程
2015/10/11 Javascript
JS使用正则表达式除去字符串中重复字符的方法
2015/11/05 Javascript
AngularJS数据源的多种获取方式汇总
2016/02/02 Javascript
谈谈target=_new和_blank的不同之处
2016/10/25 Javascript
wap手机端解决返回上一页的js实例
2016/12/08 Javascript
深入剖析Express cookie-parser中间件实现示例
2018/02/01 Javascript
vue slot 在子组件中显示父组件传递的模板
2018/03/02 Javascript
vue项目中使用ueditor的实例讲解
2018/03/05 Javascript
Vue.js实现双向数据绑定方法(表单自动赋值、表单自动取值)
2018/08/27 Javascript
如何对react hooks进行单元测试的方法
2019/08/14 Javascript
VUE实现Studio管理后台之鼠标拖放改变窗口大小
2020/03/04 Javascript
解决vue.js中settimeout遇到的问题(时间参数短效果不稳定)
2020/07/21 Javascript
ES2020让代码更优美的运算符 (?.) (??)
2021/01/04 Javascript
python实现发送邮件及附件功能
2021/03/02 Python
Python如何使用k-means方法将列表中相似的句子归类
2019/08/08 Python
Python namedtuple命名元组实现过程解析
2020/01/08 Python
python实现udp传输图片功能
2020/03/20 Python
HTML5调用手机摄像头拍照的实现思路及代码
2014/06/15 HTML / CSS
挪威太阳镜和眼镜网上商城:SmartBuyGlasses挪威
2016/08/20 全球购物
英国顶尖手表珠宝品牌独家授权经销商:HS Johnson
2020/10/28 全球购物
大整数数相乘的问题
2012/07/22 面试题
华为c/c++笔试题
2016/01/25 面试题
介绍一下Linux内核的排队自旋锁
2014/08/27 面试题
爱国演讲稿500字
2014/05/04 职场文书
2015年小班保育员工作总结
2015/05/27 职场文书
出生证明格式
2015/06/15 职场文书
「回转企鹅罐」10周年纪念展「輪るピングドラム展」海报公开
2022/03/22 日漫
vue使用wavesurfer.js解决音频可视化播放问题
2022/04/04 Vue.js
python使用BeautifulSoup 解析HTML
2022/04/24 Python