总结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 相关文章推荐
jquery JSON的解析方式
Jul 25 Javascript
javascript之bind使用介绍
Oct 09 Javascript
对之前写的jquery分页做下升级
Jun 19 Javascript
Node.js中的事件驱动编程详解
Aug 16 Javascript
jQuery滚动条插件nanoscroller使用指南
Apr 21 Javascript
jQuery简单实现彩色云标签效果示例
Aug 01 Javascript
全面解析jQuery中的$(window)与$(document)的用法区别
Aug 15 jQuery
Vue项目中使用Vux的安装过程
May 01 Javascript
vue中如何实现后台管理系统的权限控制的方法示例
Sep 19 Javascript
微信小程序云开发之云函数详解
May 16 Javascript
iview的table组件自带的过滤器实现
Jul 12 Javascript
DWR内存兼容及无法调用问题解决方案
Oct 16 Javascript
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
微信API接口大全
2015/04/15 PHP
PHP图形操作之Jpgraph学习笔记
2015/12/25 PHP
PHP中子类重载父类的方法【parent::方法名】
2016/05/06 PHP
PHP实现获取第一个中文首字母并进行排序的方法
2017/05/09 PHP
thinkphp5.1 文件引入路径问题及注意事项
2018/06/13 PHP
基于jQuery的弹出警告对话框美化插件(警告,确认和提示)
2010/06/10 Javascript
JavaScript 放大镜 移动镜片效果代码
2011/05/09 Javascript
jsPDF导出pdf示例
2014/05/02 Javascript
IE 下Enter提交表单存在重复提交问题的解决方法
2014/05/04 Javascript
javascript 寻找错误方法整理
2014/06/15 Javascript
jQuery实现不断闪烁文字的方法
2015/05/15 Javascript
jQuery实现Meizu魅族官方网站的导航菜单效果
2015/09/14 Javascript
JS利用cookie记忆当前位置的防刷新导航效果
2015/10/15 Javascript
Markdown与Bootstrap相结合实现图片自适应属性
2016/05/04 Javascript
jquery插件treegrid树状表格的使用方法详解(.Net平台)
2017/01/03 Javascript
js实现3d悬浮效果
2017/02/16 Javascript
js清除浏览器缓存的几种方法
2017/03/15 Javascript
react-router中的属性详解
2017/06/01 Javascript
解决Vue项目打包后打开index.html页面显示空白以及图片路径错误的问题
2019/10/25 Javascript
15分钟上手vue3.0(小结)
2020/05/20 Javascript
微信小程序实现带放大效果的轮播图
2020/05/26 Javascript
[01:11:46]DOTA2-DPC中国联赛 正赛 iG vs Magma BO3 第一场 2月23日
2021/03/11 DOTA
对python内置map和six.moves.map的区别详解
2018/12/19 Python
python调用百度API实现人脸识别
2020/11/17 Python
你应该知道的30个css选择器
2014/03/19 HTML / CSS
详解HTML5通讯录获取指定多个人的信息
2016/12/20 HTML / CSS
JD Sports法国:英国篮球和运动时尚的领导者
2017/09/28 全球购物
广州御银科技股份有限公司试卷(C++)
2016/11/04 面试题
建筑实习自我鉴定
2013/10/18 职场文书
销售部主管岗位职责
2013/12/18 职场文书
离婚财产分隔协议书
2014/10/23 职场文书
设立有限责任公司出资协议书
2014/11/01 职场文书
经验交流材料格式
2014/12/30 职场文书
有关西游记的读书笔记
2015/06/25 职场文书
2016形势与政策学习心得体会
2016/01/12 职场文书
CSS使用SVG实现动态分布的圆环发散路径动画
2022/12/24 HTML / CSS