1

新しいjQueryプラグインを書いています。ガイドについては、彼らの推奨事項を使用しています:

(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 ) {
            data = {
               element : this,
               target : $this,
               tooltip : tooltip
            };
            $(this).data('tooltip', data);

          }
        methods.update.apply(data.element, 'Test');
    },
    update : function( content ) { 
      var $this = $(this),
         data = $this.data('tooltip');

        // check or change something important in the data.

        private.test.apply( data.element );

        return data.element;
    }
  };

  var private = {
      test: function() {
          var $this = $(this),
            data = $this.data('tooltip');

          // again, do some operation with data
      }
  };

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

短くするためだけでなく、私の違いを示すために、彼らのバージョンとは少し異なります。基本的に、初期化では、要素に格納されるデータ オブジェクトをインスタンス化して作成しています。データ オブジェクトの一部は要素そのものです。

element : this,

次に、すべての初期化が完了したら、init からパブリック メソッドを呼び出します (機能を再利用する目的で行うとしましょう)。呼び出しを行うには、.apply() を使用し、適切なコンテキスト (my 要素) を提供します。これは、関数が外部から呼び出されるときのコンテキストと一致します。

return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));

これは問題なく理解できます。ただし、プライベート メソッドまたはパブリック メソッド内からプラグインのデータを取得するパフォーマンスについては不明です。私には、すべてのパブリックおよびプライベート メソッドの先頭で、データを取得するために次の行を実行する必要があるようです。

var $this = $(this),
     data = $this.data('tooltip');

もちろん、データに格納されているものを必要としない場合は実行しません。ただし、私のプラグインはかなりの数のアニメーションと状態追跡を実行し、ほとんどすべての機能がデータへのアクセスを必要とします。そのため、ほぼすべてのプライベートおよびパブリック呼び出しで .data() にアクセスすると、パフォーマンスが大幅に低下するようです。

私の質問は、誰かがこのプラグイン構造を使用しているかどうかです (jQuery が推奨しているので、そうであることを望んでいます)。

4

0 に答える 0