3

jqueryプラグインインスタンス(私が作成したもの)間でプロパティとメソッドを共有したいのですが、それを適切に行うにはどうすればよいですか?

次のように定義された単純なプラグインがあるとします。

// add the plugin to the jQuery.fn object
$.fn.clickableImage = function(options) {

    this.set_not_clicked = function(){
      return this.each(function() {
        $(this).addClass('not-clicked');
      });

    };

    // iterate through the DOM elements we are attaching the plugin to
    return this.each(function() {
      $(this).click( function(){
        parent.set_not_clicked() //how to get "parent" ???
        $(this).removeClass('not-clicked').addClass('clicked');
      });
    });
}

そして、次のようにインスタンス化された画像:

$(function(){
  $('#some-selector img').clickableImage();
});

「clickableImage」に他の「clickableImage」を認識させる方法は?

4

1 に答える 1

2

クロージャーは、グローバルな名前空間の汚染を防ぐため、javascript の一般的なパターンです。

詳細については、この SO の質問を参照してください: JavaScript で「閉鎖」とは正確には何を指しますか?

「クロージャー」とは、自由変数をそれらの変数をバインドする (式を「閉じる」) 環境と一緒に持つことができる式 (通常は関数) です。

あなたの場合、これは次のようになります。

(function($){
   var instances = [];
   function count(){
     alert(instances.length);
   }

   function hide_parent(){
     for(var i=0;i<instances.length;i++){
       $(instances[i]).parent().hide();
     }
   }

   $.fn.clickableImage = function(options) {

    // Use a class to prevent double bindings.       
    this
     .filter(':not(.clickImage)')
     .addClass('clickImage')
      // iterate through the DOM elements we are attaching the plugin to
     .each(function() {
        instances.push(this);
        $(this).click( function(){
          // Alert the current image count:
          count(); 
          // Hide all parents:
          hide_parent();
        })
      })

    return this;
  }
}(jQuery));

alert(typeof instances);// will return undefined

クラスを追加して、クラスの dom を検索することもできます。

$.fn.clickableImage = function(options) {
    // iterate through the DOM elements we are attaching the plugin to
    return this
      .addClass('clickImage')
      .each(function() {
      $(this).click( function(){
        $("img.clickImage").each(function(){
          $(this).parent().hide();
        });
        alert(instances_count);
      });
    });
}
于 2012-08-11T20:46:32.170 に答える