jQuery扩展方法2(转载)

我们先用最常用的插件方法创建一个库

jQuery.fn.redhome = function() {

  //库的内容

};

那么,如果要调用redhome这个方法,直接可以$obj.redhome(args)

这里解释下jQuery.fn是啥东西

jQuery = window.jQuery = window.$ = function( selector, context ) {
// The jQuery object is actually just the init constructor ‘enhanced’
return new jQuery.fn.init( selector, context );
}

jQuery.fn = jQuery.prototype = {
init: function( selector, context ) { …… }, ……
};

那么,其实很明显,$.fn.redhome其实就是jQuery.prototype.redhome,对jquery原型的扩展

这时,问题出现了,如果$符号已经被其他类库使用,那么冲突在所难免,这个时候,我们需要来创建一个闭包closure来防止$被其他库重写

(function( $ ){//闭包
  $.fn.redhome = function() {
 
    // Do your awesome plugin stuff here

  };
})( jQuery );

插件的环境

我们在调用插件的环境内,需要让this指针指向激活插件的对象。但是在一些实例中,如果调用了回调函数,this指针会指向正常的dom对象而不是jquery对象。这样经常会让程序员多余地把this指针包装一下。

(function( $ ){

  $.fn.redhome = function() {
 
    // 这里的this指向的就是jquery对象
    // $(this) 在这里就像是 $((‘#element’));
       
    this.fadeIn(‘normal’, function(){

      // this也是一个dom元素

    });

  };
})( jQuery );

参数的传递

(function( $ ){

  $.fn.redhome = function( options ) { //传入的参数options

    return this.each(function() {

      var defaults = {
        ‘location’         : ‘top’,
        ‘background-color’ : ‘blue’
      };
     
      if ( options ) {
        $.extend( defaults, options );//扩展方法原型,可以参考jQuery.extend 函数详解
      }

   //插件要执行的代码

    });

  };
})( jQuery );

这样,我们就可以调用这个方法

$(‘div’).tooltip({
  ‘location’ : ‘left’//很熟悉吧,是不是想起了css()方法
});

接下来就是命名空间的问题了

我们不推荐通过这样的方法扩展

(function( $ ){

  $.fn.redhome = function( options ) { // THIS };
  $.fn.redhomeShow = function( ) { // IS   };
  $.fn.redhomeHide = function( ) { // BAD  };
  $.fn.redhomeUpdate = function( content ) { // !!!  };

})( jQuery );

这样很明显,直接占用了$.fn.的命名空间,更好的方法我们可以通过$.fn.redhome.show或者$.fn.redhome(“show”)这样的方式来调用对应的方法。

在这个选择上,jquery ui使用了后一种

(function( $ ){

  var methods = {//这个是定义redhome内部方法的类
    init : function( options ) { // THIS },
    show : function( ) { // IS   },
    hide : function( ) { // GOOD },
    update : function( content ) { // !!! }
  };

  $.fn.redhome = function( method ) {
   
    // 调用方法
    if ( methods[method] ) {

      //把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.redhome’ );
    }   
 
  };

})( jQuery );

那么,我们就可以用$obj.redhome(“update”)来激活对应的方法,调用起来就比较方便。

原文地址:https://www.cnblogs.com/zpc870921/p/2672085.html