Jquery 插件的編寫

1. 語法:

為Jquery元素增加方法

jQuery.fn.myPlugin = function() {
  // Do your awesome plugin stuff here
};   

在Jquery命名空間增加方法

jQuery.myPlugin = function() {
  // Do your awesome plugin stuff here
};

2. 使用$代替jQuery

(function( $ ) {
  $.fn.myPlugin = function() { 
    // 在此可以使用$
  };
})( jQuery );

3. 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();

4. 帶參數

(function( $ ){
  $.fn.lockDimensions = function( type ) {  
    return this.each(function() {
    //$this 是變量,不要誤解,也可以使用其他名字
var $this = $(this); // 這裡的this是DOM對象, 所以需要使用 $(this) 轉化為JQuery對象
    if ( !type || type == 'width' ) { $this.width( $this.width() ); } if ( !type || type == 'height' ) { $this.height( $this.height() ); } }); }; })( jQuery ); $('div').lockDimensions('width').css('color', 'red');

5. Defaults and Options

使用$.extend

(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 );

6. 將所有方法封裝起來,使用methods變量存儲所有可能的方法, 這是一種好的Practice

(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'); 

7. Events

使用bind()方法可以綁定Events, 使用unbind()解除

(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');
       })
     }
       };
  $.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 );

8. Data

使用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 );

 

總結

  • 始終包含在: (function( $ ){ /* plugin goes here */ })( jQuery ); 內
  • 注意this关键字, 不要混淆
  • 使用Defaults and Options而不是傳一大堆的參數
  • methods, events and data 要有自己的命名空間
posted @ 2013-04-16 22:04  邪见  阅读(187)  评论(0)    收藏  举报