Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery bind with a different this

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
  }
}
like image 975
Abid Avatar asked Jul 01 '26 00:07

Abid


2 Answers

You can use jQuery.proxy:

$('#selector').bind('click', $.proxy(this.foo,this) );
like image 75
Engineer Avatar answered Jul 03 '26 14:07

Engineer


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); });
like image 26
Guffa Avatar answered Jul 03 '26 12:07

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!