3

関数をイベントにバインドしたいのですが、関数が呼び出されるコンテキストを変更したい

function Foo(){

  t : "123",
  bar: function(){
    // I am here
    $('#selector').bind('click' this.foo);
  }
  ,
  foo: function(){
    //I want when to be able to use the current object here by this
    //this.t should be 123 and this.bar should call the above function
  }
}
4

2 に答える 2

5

jQuery.proxyを使用できます:

$('#selector').bind('click', $.proxy(this.foo,this) );
于 2012-06-16T19:55:36.933 に答える
1

オブジェクトへの参照をローカル変数にコピーし、それを関数で使用します。

var me = this;
$('#selector').bind('click' function() { me.foo(); });

イベントオブジェクトが必要な場合は、それを渡します。

var me = this;
$('#selector').bind('click' function(e) { me.foo(e); });
于 2012-06-16T19:50:21.740 に答える