2011-07-28 9 views
0

メソッドshowAlert()を呼び出す方法プラグインへの参照をこの変数と$(this)を使ってself変数内に格納しようとしましたが、動作しないようです。ボタンのクリックイベントの中からshowAlertを呼び出しています。jqueryプラグイン内のスコープの問題

(function($){ 

     //Add your default settings values here 
     var settings = { 
     //Replace with your own settings 
     testValue:"FOO" 
     } 

     var selectedArr=[]; 
     var self=this; 

     var methods = { 
     init : function(options){ 
      return this.each(function(){ 
      //if options exists, let's merge them with our default settings 
      if(options){ 
       $.extend(settings,options); 
      } 

      var $this=$(this); 
      var button = $this.find('.schedule .time a'); 

      button.click(function(evt){ 
       evt.preventDefault(); 
       selectedArr.push($(this).addClass('selected')); 
       $(this).parent().find('input').attr('checked','checked'); 
       self.showAlert(); 
      }) 
      }); 
     } 
     } 

     showAlert: function(){ 
      alert("Please select an alternitive"); 
     } 

     //Setting namespace. Under no circumstance should a single plugin ever claim more than one namespace in the jQuery.fn object. 
     //See http://docs.jquery.com/Plugins/Authoring for an explaination of the method used here 
     $.fn.chooseAppointment = 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.chooseAppointment'); 
     } 
     }; 

    })(jQuery); 

答えて

0

あなたが書いたとおりに、showAlertthisまたはselfのメンバーではありません。ただ、このようなmethods変数の前showAlertを宣言します。

var showAlert = function() { alert("Please select an alternitive"); }; 
var methods = { /* etc etc */ }; 
+0

しかし、私はボタンイベントからどのように呼び出すのですか – Chapsterj

+0

これを使う必要はありません。 – Chapsterj

+0

なぜあなたはそれの前にvarを使用する必要がありますか?私が私の例のようにvarを外したら、どういう意味でしょう。 varなしのスコープはどれですか? – Chapsterj

0

あなたがこれを行うにはちょうど必要がありますように見える:

$('#myId').chooseAppointment('showAlert'); 

プラグインは、メソッドの引数に基づいてメソッドを呼び出し、次に渡す追加のパラメータに基づいて、他の引数を適用するように見えます。 IE

$('#myId').chooseAppoinment('showAlert', 'Foo'); 

showAlert('Foo');を呼び出すようです。

+0

あなたは '$ this.chooseAppointment( 'showAlert')を意味し;'? –

+0

私はプラグインを呼び出すページのコンテキストでコードを書いています。 – Tejs

関連する問題