2011-10-12 7 views
18

私はjavascriptオブジェクト(vr roxx :)の中にいますが、jQueryでイベントバインドを行うたびに、データパラメータを介してメインオブジェクトインスタンスのコンテキストをインクルードする必要があります。これをjQueryで簡単に行う方法はありませんか?jQueryでバインドするコンテキストを渡す方法はありますか?

var oink = 
{ 
    pig: null, 

    options:  
    { 
     showPigMom: 0 
    }, 

    init: function(pigObj) 
    { 

     //Show the pigmom 
     $(this.doc).bind('keyup click', {o: this}, function(e) 
     { 
      var o = e.data.o; 
      if (o.options.showpath) 
       o.doWhatever(); 
     }); 

    ... 
+8

$.proxy()機能を使用して...と、このオブジェクトには、彼は豚持っていた:O、e.data.o .... – Blazemonger

答えて

23

私は

init: function(pigObj) 
{ 
    //Show the pigmom 
    $(this.doc).bind('keyup click', $.proxy(function(e) { 
     if (this.options.showpath) 
      this.doWhatever(); 
     $(e.currentTarget).text(); // use this to access the clicked element 
    }, this)); 
} 
3
init: function() { 
    var self = this; 
    $(this.doc).bind('keyup click', function() { 
     if (self.options.showpath) self.doWhatever(); 
    }); 
} 
+1

$を。明示的なコンテキスト変数を持つ古い学校よりもproxy()または_.bind()が優先されるべきです。 – mPrinC

+1

'proxy'はより洗濯機に見えますが、古い学校@mPrinCの何が問題なのですか? – seebiscuit

2
init: function() { 
    $(this.doc).bind('keyup click', function() { 
     if (this.options.showpath) this.doWhatever(); 
     $(e.currentTarget).text(); // use this to access the clicked element 
    }.bind(this)) 
} 
関連する問題