总结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 字符串操作函数
Jul 25 Javascript
再谈javascript 动态添加样式规则 W3C校检
Dec 25 Javascript
加载 Javascript 最佳实践
Oct 30 Javascript
javascrpt绑定事件之匿名函数无法解除绑定问题
Dec 06 Javascript
使用jquery中height()方法获取各种高度大全
Apr 02 Javascript
javascript检查浏览器是否支持flash的实现代码
Aug 14 Javascript
JavaScript实现的圆形浮动标签云效果实例
Aug 06 Javascript
JavaScript获取服务器时间的方法详解
Dec 11 Javascript
vue实现ToDoList简单实例
Feb 07 Javascript
微信小程序实现给嵌套template模板传递数据的方式总结
Dec 18 Javascript
使用p5.js临摹动态图形
Oct 23 Javascript
react-native聊天室|RN版聊天App仿微信实例|RN仿微信界面
Nov 12 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
header跳转和include包含问题详解
2012/09/08 PHP
解析crontab php自动运行的方法
2013/06/24 PHP
PHP实现服务器状态监控的方法
2014/12/09 PHP
基于MooTools的很有创意的滚动条时钟动画
2010/11/14 Javascript
jQuery的DOM操作之删除节点示例
2014/01/03 Javascript
JS创建自定义表格具体实现
2014/02/11 Javascript
浅谈JavaScript正则表达式分组匹配
2015/04/10 Javascript
jQuery 全选 全不选 事件绑定的实现代码
2017/01/23 Javascript
javascript 动态生成css代码的两种方法
2017/03/17 Javascript
微信小程序使用radio显示单选项功能【附源码下载】
2017/12/11 Javascript
使用jQuery 操作table 完成单元格合并的实例
2017/12/27 jQuery
nodejs中密码加密处理操作详解
2018/03/20 NodeJs
NProgress显示顶部进度条效果及使用详解
2019/09/21 Javascript
JavaScript或jQuery 获取option value值方法解析
2020/05/12 jQuery
Vue文本模糊匹配功能如何实现
2020/07/30 Javascript
基于element-ui对话框el-dialog初始化的校验问题解决
2020/09/11 Javascript
[04:39]显微镜下的DOTA2第十三期—Pis卡尔个人秀
2014/04/04 DOTA
[02:00]DAC2018主宣传片——龙征四海,剑问东方
2018/03/20 DOTA
Python实现方便使用的级联进度信息实例
2015/05/05 Python
Python实现求两个csv文件交集的方法
2017/09/06 Python
Python中字符串List按照长度排序
2019/07/01 Python
python pandas获取csv指定行 列的操作方法
2019/07/12 Python
Pytorch mask-rcnn 实现细节分享
2020/06/24 Python
Python3如何使用多线程升程序运行速度
2020/08/11 Python
如何Tkinter模块编写Python图形界面
2020/10/14 Python
10个顶级Python实用库推荐
2021/03/04 Python
Cecil Mode法国在线商店:女性时尚
2021/01/08 全球购物
J2EE的优越性主要表现在哪些方面
2016/03/28 面试题
自考毕业自我鉴定范文
2013/10/27 职场文书
秋季开学典礼主持词
2014/03/19 职场文书
反邪教警示教育方案
2014/05/13 职场文书
机械电子工程专业自荐书
2014/06/10 职场文书
2014年乡镇个人工作总结
2014/12/03 职场文书
二十年同学聚会感言
2015/07/30 职场文书
缅怀先烈主题班会
2015/08/14 职场文书
python xlwt模块的使用解析
2021/04/13 Python