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
}
}
You can use jQuery.proxy:
$('#selector').bind('click', $.proxy(this.foo,this) );
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With