总结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 相关文章推荐
js的.innerHTML = &quot;&quot;IE9下显示有错误的解决方法
Sep 16 Javascript
js动态创建上传表单通过iframe模拟Ajax实现无刷新
Feb 20 Javascript
JavaScript返回当前会话cookie全部键值对照的方法
Apr 03 Javascript
javascript实现二级级联菜单的简单制作
Nov 19 Javascript
基于bootstrap插件实现autocomplete自动完成表单
May 07 Javascript
H5移动端图片压缩上传开发流程
Nov 09 Javascript
jQuery 的 ready()的纯js替代方法
Nov 20 Javascript
javascript实现日期三级联动下拉框选择菜单
Dec 03 Javascript
JS奇技之利用scroll来监听resize详解
Jun 15 Javascript
实例讲解DataTables固定表格宽度(设置横向滚动条)
Jul 11 Javascript
小程序实现左滑删除效果
Jul 25 Javascript
element的el-table中记录滚动条位置的示例代码
Nov 06 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
php中长文章分页显示实现代码
2012/09/29 PHP
Yii中srbac权限扩展模块工作原理与用法分析
2016/07/14 PHP
php生成毫秒时间戳的实例讲解
2017/09/22 PHP
PHP实现的基于单向链表解决约瑟夫环问题示例
2017/09/30 PHP
Laravel框架实现修改登录和注册接口数据返回格式的方法
2018/08/17 PHP
laravel-admin解决表单select联动时,编辑默认没选上的问题
2019/09/30 PHP
NodeJS框架Express的模板视图机制分析
2011/07/19 NodeJs
js模仿windows桌面图标排列算法具体实现(附图)
2013/06/16 Javascript
实现51Map地图接口(示例代码)
2013/11/22 Javascript
javascript版2048小游戏
2015/03/18 Javascript
JS中使用apply方法通过不同数量的参数调用函数的方法
2016/05/31 Javascript
浅谈toLowerCase和toLocaleLowerCase的区别
2016/08/15 Javascript
jQuery实现弹出带遮罩层的居中浮动窗口效果
2016/09/12 Javascript
JS遍历对象属性的方法示例
2017/01/10 Javascript
BootStrap中的Fontawesome 图标
2017/05/25 Javascript
node.js基于dgram数据报模块创建UDP服务器和客户端操作示例
2020/02/12 Javascript
基于vue实现简易打地鼠游戏
2020/08/21 Javascript
浅谈javascript事件环微任务和宏任务队列原理
2020/09/12 Javascript
[01:05:36]VP vs TNC Supermajor小组赛B组 BO3 第二场 6.2
2018/06/03 DOTA
python学习笔记:字典的使用示例详解
2014/06/13 Python
深入理解Python中字典的键的使用
2015/08/19 Python
Python数据分析之获取双色球历史信息的方法示例
2018/02/03 Python
TensorFlow实现随机训练和批量训练的方法
2018/04/28 Python
python爬取微信公众号文章的方法
2019/02/26 Python
python实现图片九宫格分割
2021/03/07 Python
Python 中如何实现参数化测试的方法示例
2019/12/10 Python
基于python 取余问题(%)详解
2020/06/03 Python
HTML5离线缓存在tomcat下部署可实现图片flash等离线浏览
2012/12/13 HTML / CSS
美国职棒大联盟的官方手套、球和头盔:Rawlings
2020/02/15 全球购物
面试后的感谢信范文
2014/02/01 职场文书
人力资源部经理岗位职责规定
2014/02/23 职场文书
元旦标语大全
2014/10/09 职场文书
期中考试后的感想
2015/08/07 职场文书
岗位聘任协议书
2015/09/21 职场文书
优秀范文:读《红岩》有感3篇
2019/10/14 职场文书
JS不要再到处使用绝对等于运算符了
2021/04/30 Javascript