0

我试图更好地理解如何创建 jQuery 插件,并且我的理解基于http://docs.jquery.com/Plugins/Authoring。我在最后,对命名空间和数据感到困惑。

首先(参见下面代码中的问题 1):本教程显示目标 ( $this) 和工具提示都存储在对象字面量中。

  1. 存储这些特定变量有什么好处?
  2. 如果有默认值和自定义选项,这是保存结果设置对象的好地方吗?

另外,他们这样做是有原因$(this).data('tooltip',{target:$this,tooltip:tooltip});的,而不是$this.data('tooltip',{target:$this,tooltip:tooltip});

第二(参见下面代码中的问题 2):本教程展示了如何销毁插件。我明白$this.removeData('tooltip');了,但是这样做有什么意义data.tooltip.remove();呢?

来源:http ://docs.jquery.com/Plugins/Authoring#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
           */

           //QUESTION 1
           $(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');

         QUESTION 2
         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 );
4

1 回答 1

1

存储这些特定变量有什么好处?

存储在data对象中的变量在调用时可供其他方法使用。

  • 目标:我使用过这种插件模式,但从未发现有必要存储target:$this. $(this).data但是,在某些情况下,在复杂的插件方法中传递可能会很方便。data.target让您可以自由地执行此操作,同时仍然可以让您回到原来的状态$(this)。可能还有其他原因,但我不知道。

  • tooltip :无疑需要被其他方法使用,参见例如。destroy方法。

    如果有默认值和自定义选项,这是保存结果设置对象的好地方吗?

是的,settings可以存储在data对象中,如果其他方法需要访问设置,无论它们是否已被选项扩展,这样做通常很方便。

另外,他们这样做是有原因$(this).data('tooltip',{target:$this, tooltip:tooltip});的,而不是$this.data('tooltip',{target:$this,tooltip:tooltip});

不,没有理由。$this显然在范围内,使用它而不是 re-wrapping 会更有效this

第二(参见下面代码中的问题 2):本教程展示了如何销毁插件。我明白$this.removeData('tooltip');了,但是做 data.tooltip.remove(); 有什么意义?

data.tooltip.remove();<div />从 DOM中删除动态生成的元素。如果它没有被移除,那么工具提示将不会被完全销毁。

于 2012-10-26T02:16:57.250 回答