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

 更新时间:2016年05月16日 16:35:49   作者:arthinking  
这篇文章主要介绍了总结jQuery插件开发中的一些要点,包括命名空间与事件events等重点和难点部分的讲解,要的朋友可以参考下

基础
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 );

相关文章

  • jQuery实现表格展开与折叠的方法

    jQuery实现表格展开与折叠的方法

    这篇文章主要介绍了jQuery实现表格展开与折叠的方法,涉及jQuery中toggleClass方法与链式操作的相关技巧,非常简单实用,需要的朋友可以参考下
    2015-05-05
  • jquery子元素过滤选择器使用示例

    jquery子元素过滤选择器使用示例

    jquery子元素过滤选择器在某些特殊的情况下还是比较实用的,下面为大家介绍下具体的使用方法,感兴趣的各位可以参考下哈
    2013-06-06
  • jQuery Validate表单验证深入学习

    jQuery Validate表单验证深入学习

    这篇文章主要介绍了jQuery Validate表单验证入门知识,该插件捆绑了一套有用的验证方法,包括 URL 和电子邮件验证,同时提供了一个用来编写用户自定义方法的 API,感兴趣的小伙伴们可以参考一下
    2015-12-12
  • JQuery扩展插件Validate 2通过参数设置验证规则

    JQuery扩展插件Validate 2通过参数设置验证规则

    在前面示例中使用的的方法简单方便,但没有完全将js与页面结构完全分离,也就是说js依赖了class,下面通过validate()方法的参数设置验证规则将js与页面结构完全分离
    2011-09-09
  • jQuery避免$符和其他JS库冲突的方法对比

    jQuery避免$符和其他JS库冲突的方法对比

    jQuery中需要用到$符号,如果其他js库也定义了$符号,那么就会造成冲突,会影响到js代码的正常执行,下面有几个不错的解决方法,大家可以参考下
    2014-02-02
  • jQuery完成表单验证的实例代码(纯代码)

    jQuery完成表单验证的实例代码(纯代码)

    这篇文章主要介绍了jquery完成表单验证的实例代码,代码简单易懂,需要的朋友可以参考下
    2017-09-09
  • jQuery插件FusionCharts绘制的2D双面积图效果示例【附demo源码】

    jQuery插件FusionCharts绘制的2D双面积图效果示例【附demo源码】

    这篇文章主要介绍了jQuery插件FusionCharts绘制的2D双面积图效果,结合实例形式分析了jQuery使用插件FusionCharts结合xml格式数据绘制2D双面积图的具体步骤与相关操作技巧,并附带demo源码供读者下载参考,需要的朋友可以参考下
    2017-04-04
  • jQuery的实现原理的模拟代码 -3 事件处理

    jQuery的实现原理的模拟代码 -3 事件处理

    在 jQuery 中,实际注册的事件处理函数是一个匿名的闭包函数,这个函数最终都是通过调用 jQuery.event.handle 进行处理的。
    2010-08-08
  • jQuery中prepend()方法用法实例

    jQuery中prepend()方法用法实例

    这篇文章主要介绍了jQuery中prepend()方法用法,以实例形式较为详细的分析了prepend()方法的功能、定义及使用技巧,并对比分析了与text()方法的不同之处,需要的朋友可以参考下
    2014-12-12
  • 基于jQuery的实现简单的分页控件

    基于jQuery的实现简单的分页控件

    分页控件需要向后台发送请求,发送的参数包括当前页,每页显示数量,查询条件;并且获取数据加载到当前页面
    2010-10-10

最新评论