jQuery用不同的绑定

时间:2022-11-17 19:12:26

I want to bind a function to an event but I want to change the context in which the function is called

我想将一个函数绑定到一个事件,但我想更改调用该函数的上下文

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
  }
}

2 个解决方案

#1


5  

You can use jQuery.proxy:

你可以使用jQuery.proxy:

$('#selector').bind('click', $.proxy(this.foo,this) );

#2


1  

Copy the reference to the object to a local variable, and use it in a function:

将对象的引用复制到局部变量,并在函数中使用它:

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

If you need the event object, pass that on:

如果您需要事件对象,请将其传递给:

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

#1


5  

You can use jQuery.proxy:

你可以使用jQuery.proxy:

$('#selector').bind('click', $.proxy(this.foo,this) );

#2


1  

Copy the reference to the object to a local variable, and use it in a function:

将对象的引用复制到局部变量,并在函数中使用它:

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

If you need the event object, pass that on:

如果您需要事件对象,请将其传递给:

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