28

ほとんどの jQuery プラグインは、最初に初期化するときに DOM ノードに結び付けられます。

$('#foo').bar({options: ...});

のような DOM ノードに現在バインドされているプラ​​グインまたはオブジェクトを確認するにはどうすればよいです#fooか?

if($('#foo').bar)
if($.inArray('bar', $('#foo').eq(0)))
if($('#foo').eq(0).indexOf('bar'))
if($('#foo').hasOwnProperty('bar'))

たとえば、次のようにオブジェクトにバインドされたイベントを取得できます。

console.log($('#foo').data('events'));
4

3 に答える 3

9

プラグイン自体が、作業中の要素を変更する何らかの方法を定義していない限り、それは不可能です。例えば:

$.fn.extend({
  foo: function() { console.log("I am foo!"); }
});

$('#bar').foo();

ここでは、呼び出し元の要素と対話しようとさえしない、完全な (まあまあまあの) jQuery プラグインを定義しました。それでも、jQuery でラップされた要素のコレクションでは、次の行によりプロトタイプこのメソッドが含まれているため、必要に応じてそれを使用できます (からjquery.js)。

jQuery.fn = jQuery.prototype = { ... }

...$.fn.extendそのプラグインをプラグインするために呼び出された後、しゃれは意図されていません。

しかし、私のプラグインが呼び出し要素を何らかの方法で変更する必要があったとしても、次のようになります。

$.fn.extend({
  bar: function() { this.html('I am all bar now!'); }
});
$('#bar').bar();

...基本的に、内部のjQueryロギングだけに依存するのではなく、いくつかの外部イベント(DOMミューテーションのもの)でこれを処理する必要があります。

于 2012-10-30T17:08:00.050 に答える
4

私の場合、検出しようとしていたプラグインが、たまたま要素$(element).data()ストアにデータを追加していました。また、プラグインがクラスまたは ID を追加し、その名前または名前を変更したものも見てきました。

以下は、この問題を解決するために現在取り組んでいるコードです。ただし、ほとんどのプラグインでは機能しない可能性があります。

$.fn.extend({
    isPluginBound: function(pluginName)
    {
        if(jQuery().pluginName)
        {
            var name = pluginName.toLowerCase();

            return this.data(pluginName) || this.data(name)
                || this.attr('class').toLowerCase().indexOf(name) !== -1 // vs hasClass()
                || this.attr('id').toLowerCase().indexOf(name) !== -1;
        }
    }
});

それを使用するには、呼び出すだけです$('#foo').isPluginBound('bar');

于 2012-10-30T17:42:28.407 に答える
1

私が知る限り、すべての jQuery ウィジェットはインスタンスを DOM ノードに追加します。私のプロジェクトで次の拡張機能を使用しています。名前がわからないウィジェットのメソッドを呼び出すのも便利です (たとえば、拡張ウィジェットの基本メソッドを呼び出す)。

// returns first found widget instance of the first element or calls method on first widget instance of all elements
$.fn.widget = function ( method , option, value ) { 
  var wi;
  // iterate all elements 
  this.each( function() {
    var wii;
    // iterate all attached data elements, look for widget instances
    $.each( $(this).data(), function( key, data ){ 
      if ( "widgetName" in data ){ wii = data; return false } 
    })
    // if there is a widget instance but no method specified
    if ( wii && !method ) {
      wi = wii;
      return false
    }
    // if there is a widget and there is an object found with the method as the key
    else if ( wii && ( method in wii ) ) {
      // if it is truly a method of that instance, call that instance
      if ( $.isFunction( wii[method] ) ) {
        wi = wii[method].call( wii, option, value )
      } 
      // else, it is maybe a value stored in the instance you seek?
      else {
        wi = wii[method]
      }
    }
  })
  return ( wi === undefined ) ? this : wi ;
}
于 2012-10-30T17:57:51.830 に答える