Reputation: 7227
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
}
}
Upvotes: 3
Views: 207
Reputation: 48813
You can use jQuery.proxy:
$('#selector').bind('click', $.proxy(this.foo,this) );
Upvotes: 5
Reputation: 700910
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); });
Upvotes: 1